iTranslated by AI
Tips for Reducing Unnecessary Re-renders in Valtio
Introduction
I have recently been using valtio, a simple state management library.
It manages state with mutable proxy objects, and by directly updating these proxy objects, you can update the state from anywhere.
When referencing a proxy object within a React component, updating the proxy object does not automatically trigger a re-render of the component. To trigger a re-render upon an update, you need to obtain a snapshot of the proxy object using the useSnapshot hook.
I initially lacked a deep understanding of how this snapshot-based rendering behavior worked, which led to unnecessary re-renders.
Therefore, I am documenting methods to avoid increasing these unnecessary re-renders.
In short
Obtaining the snapshot using useSnapshot within the component that references it is the best way to reduce re-renders.
If you obtain a snapshot and then pass it down through components (prop drilling), re-renders will increase.
I will explain why this is the case below.
Incorrect snapshot placement leads to unnecessary re-renders
Suppose you have a proxy object with two properties as follows:
const state = proxy({ a: false, b: false });
Let's assume there are components A and B that display these properties respectively.
To re-render components in response to updates in the proxy object, you would naturally use useSnapshot to obtain a snapshot.
const snapshot = useSnapshot(state)
Previously, I thought that taking a snapshot of a proxy object meant that if any part of the object's properties were updated, every location obtaining a snapshot of that object would re-render.
In this example, I thought that updating a part of the property, such as state.a = true, would trigger a re-render in all locations where const snapshot = useSnapshot(state) was called.
Therefore, I believed there was almost no difference in rendering cost between A. Getting the snapshot in the parent component first and passing it to child components and B. Getting the snapshot in each child component individually. I even thought that method A was better because it reduced the number of useSnapshot calls. (Details of the code are in the accordion)
A. Get the snapshot in the parent component first and pass it to child components
const state = proxy({ a: false, b: false });
const ComponentA = (snapshot) => {
console.log("a rerendered");
return (
<button onClick={() => (state.a = !state.a)}>{`A ${snapshot.a}`}</button>
);
};
const ComponentB = (snapshot) => {
console.log("b rerendered");
return (
<button onClick={() => (state.b = !state.b)}>{`B ${snapshot.b}`}</button>
);
};
const App = () => {
const snapshot = useSnapshot(state);
return (
<>
<div>App Component</div>
<ComponentA snapshot={snapshot} />
<ComponentB snapshot={snapshot} />
</>
);
};
export default App;
B. Get the snapshot in each child component
const state = proxy({ a: false, b: false });
const ComponentA = () => {
const snapshot = useSnapshot(state);
console.log("a rerendered");
return (
<button onClick={() => (state.a = !state.a)}>{`A ${snapshot.a}`}</button>
);
};
const ComponentB = () => {
const snapshot = useSnapshot(state);
console.log("b rerendered");
return (
<button onClick={() => (state.b = !state.b)}>{`B ${snapshot.b}`}</button>
);
};
const App = () => {
return (
<>
<ComponentA />
<ComponentB />
</>
);
};
However, it turns out that valtio optimizes by watching the accessed properties within the snapshot and only triggering a re-render when those specific elements are changed. (If you obtain a snapshot of an object, a re-render is not blindly triggered when any part of that object's properties is updated; it is triggered only by updates to the accessed properties within the snapshot.)
This is also clearly stated in the official documentation as of 2023/10/9:
The component will only re-render when the parts of the state you access have changed, it is render-optimized.
Therefore, while method A causes both components to re-render when one property is updated, method B makes it possible to re-render only the relevant component.
Thus, even if the snapshot obtained is the same, obtaining the snapshot in each child component individually results in fewer re-renders than obtaining it in the parent component and passing it down.
(By the way, if you take a snapshot but do not access any properties, it will monitor changes to all properties and trigger a re-render.)
const ComponentA = () => {
useSnapshot(state); // Re-renders when either property a or b changes.
console.log("a rerendered");
return (
<button onClick={() => (state.a = !state.a)}>{`A ${state.a}`}</button>
);
};
Notes on taking a snapshot of an array
Be aware that taking a snapshot of an array can easily cause unnecessary re-renders.
Here, let's assume we have an array proxy object.
const arrayState: {a: boolean}[] = proxy([{a: true}, {a: false}]);
To execute a re-render when an element is added to or deleted from this object, you need to map over the snapshot.
const ParentComponent = () => {
const snapshot = useSnapshot(arrayState);
return snapshot.map((s, index) => (<ChildComponent snapshot={s} index={index} />));
}
const ChildComponent = (snapshot: {a: boolean}, index: number) => {
return <button onClick={() => (arrayState[index].a = !arrayState[index].a)}>{`${snapshot.a}`}</button>;
}
In this case, mapping over an array snapshot causes re-renders in the parent component and all child components when any element of the array is updated. (It seems that mapping over an array snapshot is considered as accessing all elements of the snapshot.)
const ParentComponent = () => {
const snapshot = useSnapshot(arrayState);
return snapshot.map((s) => (<ChildComponent snapshot={s} index={index} />));
}
const ChildComponent = (snapshot: {a: boolean}, index: number) => {
// Clicking the button to update one element in the array
// re-renders the parent component and all child components.
return <button onClick={() => (arrayState[index].a = !arrayState[index].a)}>{`${snapshot.a}`}</button>;
}
I have found two ways to avoid this.
It seems a good method to pass the proxy, not the snapshot, to child components and memoize the child components so they don't re-render even if the parent component re-renders.
const ParentComponent = () => {
const snapshot = useSnapshot(arrayState);
// Map with snapshot, but pass proxy instead of snapshot to children
return snapshot.map((_, index) => (<ChildComponent proxy={arrayState[index]} />));
}
const ChildComponent = memo(function ChildComponent({proxy}: {proxy: {a: boolean}}) {
const snapshot = useSnapshot(proxy);
return <button onClick={() => (proxy.a = !proxy.a)}>{`${snapshot.a}`}</button>;
});
Editing a part of the child elements does trigger a re-render of the parent component itself, but by memoizing the child components, you can prevent re-renders of child components other than the one being edited.
Another way to prevent re-renders of all child components (some cases might not work normally)
Instead of mapping over the snapshot, mapping over the range of the snapshot length prevents a full re-render when editing one child element.
const ParentComponent = () => {
const snapshot = useSnapshot(arrayState);
// range(snapshot.length).map instead of snapshot.map
return range(snapshot.length).map((_, index) => (<ChildComponent proxy={arrayState[index]} />));
}
const ChildComponent = (proxy: {a: boolean}) => {
const snapshot = useSnapshot(proxy)
return <button onClick={() => (proxy.a = !proxy.a)}>{`${snapshot.a}`}</button>;
}
However, this method does not trigger a re-render when swapping elements in the array. Therefore, this method is not suitable if you want to perform swaps. Conversely, if you don't need to swap, memoizing child components is not necessary, making it easier to implement.
Conclusion
Valtio seems to monitor the properties accessed in a snapshot and triggers a re-render only when those properties are updated.
To avoid causing unnecessary re-renders, it is generally better to obtain the snapshot within the component that references it. (Do not pass snapshots as props.)
Be careful when taking a snapshot of an array, as it is prone to unnecessary re-renders.
Discussion
そう、そうなんです。直感に反する場合もあるのですが、この方が自然なのです。