Zustand Performance Study

Zustand is one of the most excellent lightweight state management libraries for React and other frameworks. However, certain coding practices may result in decreased performance. Here are some of the most common ones I’ve discovered in my study.

Avoid Destructuring the Store Hook

const { name } = useUserStore(state => state); 
// or 
const { name } = useUserStore();
JavaScript

vs

const name = useUserStore(state => state.name)
JavaScript

The first impacts performance by triggering unnecessary re-renders of the component. This occurs because the store hook subscribes an observable to the component and constantly checks for state changes. As the state is typically an object, its memory address changes with each execution, leading to the component being re-rendered every time, regardless of whether the state has actually changed or not.

On the contrary, the latter enhances performance by solely checking the property name of the state object, which is a String type. The component re-renders only when the name property is updated to a new value. Hence, it eliminates unnecessary re-rendering and delivers significantly improved performance.

UseShallow for Enhanced Performance

Within Zustand, a beneficial native hook named useShallow proves invaluable for optimizing performance:

const { name } = useUserStore(useShallow(state => state))
JavaScript

Essentially, useShallow conducts a deep comparison of objects instead of solely checking reference addresses. This allows for the use of destructuring without making a performance hit.

Using this feature makes it easier to write more advanced and straightforward code, as shown below:

Selecting multiple values with single line of code

const { name, age } = useUserStore(useShallow(state => return{ state.name, state.age } ));
const [ name, age ] = useUserStore(useShallow(state => [ state.name, state.age ] ));
JavaScript

By using useShallow, you can elegantly select multiple values in a single line, enhancing both readability and performance.

Avoid Extracting Functions from the Store Hook

This topic is deeply explained in the following post:
https://www.codezimple.com/optimal-practices-for-organizing-zustand-store/.

Leave a Reply

Your email address will not be published. Required fields are marked *