You can optimize the reactivity in your app by using shallowRef
:
const user = shallowRef({name: 'Michael',friends: [{name: 'Travis',friends: [// ...],},{name: 'Matthew',friends: [// ...],},]});
Reactivity is only triggered when the value
of the ref
itself is changed:
// Triggers a reactive updateuser.value = matthew;
But modifying any of the nested properties won’t trigger anything:
// Nothing happensuser.value.name = 'Martin';
Adding deep reactivity to a large object can cost you a lot of performance, so this can be useful for saving some CPU cycles.
You can also manually trigger a reactive update if it’s necessary:
// Log the user whenever it changeswatchEffect(() => console.log(user));// Update nested state (no log happens)user.value.name = 'Martin';// Force a reactive update to triggertriggerRef(user);// [user object]
Here are the docs for shallowRef and triggerRef.