When it comes to state management library the first thing that comes to mind is Redux and I think redux does the job pretty well but it becomes overkill for small projects. To fix this issue there are lots of libraries and one of them is Zustand. Let's try to understand why and when to consider zustand.
What is Zustand?
Zustand is a lightweight, fast, scalable, and open-source state management library for react based on hooks with no boilerplate. It works on the same flux principles as redux. As of today it has more than 350000 Weekly downloads.
Why Zustand?
So you might be thinking isn't it the same as redux, What's the difference then? Here's some key features which make it different.
- Simple API (With almost no boilerplate)
- Lightweight (Almost 1.5kb in size)
- Supports asynchronous action out the box
- Un-opinionated
It also uses some performance optimisation techniques like memoization. Let's understand this with an example.
Letβs assume we have a state model { apples: 1, oranges: 1 }
and two component one uses apples
and another uses oranges
. Now in case of context api or redux any one of these state changes will re-render both components but in case of Zustand it will render only component which is consuming the particular state.
function Apples() {
// This component will *only* render when the amount of apple changes
const apples = useStore(state => state.apples)
return <div>{apples}</div>
}
Now that we know it is better for some use cases like small applications which need small data to be stored globally let's take a look at its implementation.
Adding zustand to our project
- Create a store.
import create from 'zustand'
const useStore = create(set => ({
bears: 0,
increasePopulation: () => set(state => ({ bears: state.bears + 1 })),
removeAllBears: () => set({ bears: 0 })
}))
- Start accessing the data inside store.
Getting total bear counts.
function BearCounter() {
const bears = useStore(state => state.bears)
return <h1>{bears} around here ...</h1>
}
Calling increment function.
function Controls() {
const increasePopulation = useStore(state => state.increasePopulation)
return <button onClick={increasePopulation}>Add bear</button>
}
Handling async actions
import axios from "axios";
const useStore = create(set => ({
bears: 0,
getMoreBears: async () => {
const response = await axios.get('api endpoint')
set({ bears: response.data })
}
}))
That's pretty much it. In just a few lines of code, you can setup your global state.
Hope it will save some of your time. Let's catch up in the next one until then goodbye.
Top comments (1)
Another awesome tool in my toolbox, going to try this in my next projects for sure. π