This page looks best with JavaScript enabled

Make an object non-reactive in Vue

 ·   ·  ☕ 2 min read

Are you tired of Vue reactivity? Do you long for days when you had to manually refresh HTML pages to see changes? Or, do you have large objects and reactivity is killing your app? Vue has the answer.

Vue enables this magic to respond to any changes in state on the UI. You can just declare variables in a component, and low and behold - they are reactive.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
<script>
  export default {
    data() {
      return {
          accounts:[],
      };
    },
    mutations: {
      setAccounts(state, accounts) {
          state.accounts = accounts
      },
      addAccount(state, account) {
        state.accounts.push(account);
      }
    };
  }
</script>

In the above example, accounts is reactive. Any changes to accounts is reflected on the UI without needing any other changes or logic.

However, you may want this reactivity to stop for large objects.

You see Vue internally keeps track of states and any changes. Any change to large objects may need Vue to do quite a bit of work in recognizing those changes, not to mention the memory requirements of all the paraphernalia required to track states.

You can easily stop making state reactive by using Object.freeze().

1
2
3
4
5
6
7
8
9
<script>
  export default {
    const mutations = {
      setAccounts(state, accounts) {
        state.accounts = Object.freeze(accounts);
      }
    };
  }
</script>

The above code will set the accounts state and also signify that there is no state tracking required since the object is frozen anyway.

Object.freeze() does not mean that you cannot change the object. You can do setAccounts as usual and reset accounts as normal.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things