Redux vs Zustand for state management in React app
"A JS library for predictable and maintainable global state management" - Redux
"A small, fast, and scalable bearbones state management solution" - Zustand
Let us understand the concept of state management in React application first.
State management in React refers to the way data is managed and updated within a React application. React components can have their own local state (component state) which allows them to manage and update data without directly affecting other components.
Let us see practically how to implement a simple state management application with both Redux and Zustand individually to understand the differences .
Counter state with Redux(Centralised state store)
2. Create state slice with createSlice() function and add
{ counter1:100,counter2:200} as initial state
3. Add this reducer to redux store
4. Provide the redux store to Root/Parent component.
Now, this store is accessible by every component of the application.
5. Consume this store in component.
Note-Never access whole state(Both in Redux and in Zustand) in a Component. It leads to multiple re-renders. i.e. If a component needs counter1, then select only counter1 instead of the entire state which includes counter2 too. For example , if you write
let {counter1}=useSelector(state=>state) <- This is wrong
Then you can see this warning in console.
This warning is self explanatory . That selector will re-render a component either counter1 or counter2 is changed.
Let us create two components where one can consume counter1 & other counter2
领英推荐
Now, when counter1 is changed then , only TestReduxCounter1.jsx will be re-rendered. In the same way, for counter2 it is TestReduxCounter2.jsx.
In this way, the state management can be implemented using Redux in React application
Counter state with Zustand (Hook based state management)
It's like a custom hook, so that name should start with "use".
2. Select counter1 & changeCounter1 function in a component & counter2 & changeCounter2 in another component.
That's it.
Note- I have added console statement in every component to check re-rendering
Observations
Redux:
Zustand
Choosing Between Redux and Zustand
Kindly let me know if i miss any valid point in this.
Associate Engineer at Cognizant Technologies
9 个月Helpful ??