Make an object non-reactive in Vue

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.

<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().

<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.

comments powered by Disqus