React state management with zustand
Before delving into Zustand, let's take a moment to understand the concept of global state management in React, which involves storing and managing the state of your application in a centralized location to be accessed and updated by any component that requires it.
What is Zustand?
Zustand is a state management solution designed to be small, fast, and scalable. It simplifies the Flux architecture and is built on top of React hooks, making it easy to use without requiring significant boilerplate code. Zustand is one of the smallest state management libraries with a bundle size of just 1.16kb. With over 30.4k stars, which is more than redux, mobX and jotai on GitHub, Zustand has gained popularity among developers for its simplicity and ease of use, making it a top choice for state management in React applications.
It is straightforward to use and integrate. Some of its features are:
Zustand vs Redux!
Redux is a robust library that provides advanced features for managing application state in a flexible manner. It is commonly utilized in larger and more intricate software applications, which necessitate a more powerful approach to state management. Although it entails more setup and learning to use effectively, Redux can be implemented not only with React but also in other scenarios.
In the provided code sample, Redux Toolkit is used instead of Redux because it simplifies the code. The store is initialized by creating a reducer or slice which holds the application state. Through this store, the state can be updated, and changes to the state will trigger re-rendering of any components that depend on that state.
import { createSlice } from '@reduxjs/toolkit'
const initialState = {
value: 0,
}
export const counterSlice = createSlice({
name: 'counter',
initialState,
reducers: {
increment: (state) => {
// Redux Toolkit allows us to write "mutating" logic in reducers.
// It doesn't actually mutate the state because it uses the Immer library,
// which detects changes to a "draft state" and produces a brand new
// immutable state based off those changes
state.value += 1
},
decrement: (state) => {
state.value -= 1
},
incrementByAmount: (state, action) => {
state.value += action.payload
},
},
})
// Action creators are generated for each case reducer function
export const { increment, decrement, incrementByAmount } = counterSlice.actions
export default counterSlice.reducer
To use the increment and decrement actions, the useSelector and useDispatch hooks need to be imported. While this approach provides more flexibility and speed, the syntax and API can be complex. Personally, I find it cumbersome to create all the necessary boilerplate code for simple tasks.
import React from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { decrement, increment } from './counterSlice'
export function Counter() {
const count = useSelector((state) => state.counter.value)
const dispatch = useDispatch()
return (
<div>
<div>
<button
aria-label="Increment value"
onClick={() => dispatch(increment())}
>
Increment
</button>
<span>{count}</span>
<button
aria-label="Decrement value"
onClick={() => dispatch(decrement())}
>
Decrement
</button>
</div>
</div>
)
}
When it comes to zustand just look at the below code and you will see the beauty of the zustand. We have a zustand store and reducer all you need to do to import create from zustand and it gonna give you the callback that has a set function. the set is basically just to update any kind of variable inside of the store. You have the initial state and its default value and have the action that is increasePopulation and removeAllBrears and those actions are going to call the set and you can update whatever you want that's it. It’s pretty simple no more boilerplate code. the useStore going to return a hook that you can use inside your components.
领英推荐
import { create } from 'zustand'
const useStore = create((set) => ({
bears: 0,
increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
removeAllBears: () => set({ bears: 0 }),
}))'
With the useStore hook, you can easily access the state and actions you need without the need to wrap your components in a provider or worry about nested code. This makes the code much simpler and easier to read compared to using Redux. Plus, you don't have to concern yourself with when the component will re-render, since the hook takes care of all that for you. It just hooks and it makes the thing look a lot simpler and the code is so much easier to read as compared to redux.
function BearCounter() {
const bears = useStore((state) => state.bears)
return <h1>{bears} around here...</h1>
}
function Controls() {
const increasePopulation = useStore((state) => state.increasePopulation)
return <button onClick={increasePopulation}>one up</button>
}
The question of whether to drop Redux and switch to Zustand is a common one. However, the simple answer is No. Both libraries have their strengths and weaknesses, and the choice ultimately depends on the specific project requirements.
Zustand is a lightweight state management library that is suitable for smaller projects or applications with less complex state needs. It provides a simple and intuitive API and can be used to manage state in a more direct and concise way than Redux.
On the other hand, Redux is a more robust state management library that is better suited for large-scale projects or applications with complex state requirements and longer development periods. It provides a more structured and standardized approach to state management, which can help to maintain consistency and facilitate collaboration among team members.
In summary, both Zustand and Redux have their place in modern web development, and the choice depends on the specific needs and constraints of each project.
You can check more on their official sites that I have mentioned below.
I hope the information I shared has been helpful, and please feel free to share any tips you may have. These insights are based on my own experiences, and I believe there is always more to learn.
Full Stack Developer @ Quicktext || Javascript Instructor
10 个月Thank you favour ... a new goal to achieve ??
Helping 100+ frontend devs escape tutorial hell + build modular & scalable component-based apps using React.
10 个月?? I love Redux, especially Redux Toolkit. I've never tried Zustand before though. So I guess I'm a budding knight in training ?? Keep been amazing Rafik.
Software Engineer
10 个月Zustand can be scaled for large applications. Redux -> opinionated (complex , bigger bundle size, slower …). Zustand -> unopinonated(lightweight, simple ,better mutation handling , better performance…).