Zustand is a small, fast, and scalable state management library for React. It provides a simple API for managing both global and local state without the complexity of other state management tools.
How will you send data from child to parent component or how will you share data with sibling component, all that complexity is solved by Zustand.
I personally prefer Zustand over Redux because it is much simpler to use and has a smaller bundle size. It is also easier to understand and debug.
To install and configure Zustand with ReactJs head over tohere
Be careful while importing the store. If you import all the functions and state in a single import, it will cause the component to re-render whenever the state changes. Instead, import only the required functions and state.
Zustand also provides a method to use and updates states outside of a React Component.
See updating the nested object is a bit complex and can be hard to understand. But with Immer middleware you only need to update the required key and Immer will take care of the rest.
Zustand also provides a way to persist the state even after the page is refreshed. You can use the persist middleware to achieve this. The data is stored in Local Storage/Session Storage/IndexedDB.
It becomes very convenient to store the user's theme preference, language preference, or any other data that you want to persist.
persist also takes a second argument which is an object with the following properties:
name: The name of the storage key.
getStorage: A function that returns the storage object. By default, it uses localStorage. You can also use sessionStorage or indexedDB.
Like this:
Here ends the basic use of Zustand to manage states. Thank you for reading, Shukriya 💐