What is Zustand?
Zustand is a small yet powerful state management library for React. Unlike Context API, which can cause unnecessary re-renders, Zustand offers global state with minimal re-renders and a simple API.
Setting Up Zustand
To install Zustand, run:
npm install zustand
Now, let’s create a basic store:
import { create } from "zustand";
const useStore = create((set) => ({
count: 0,
increase: () => set((state) => ({ count: state.count + 1 })),
}));
function Counter() {
const { count, increase } = useStore();
return <button onClick={increase}>Count: {count}</button>;
}
Here, useStore
acts as a global state store, and increase
updates the count without unnecessary re-renders.
Practical Use Cases
1. Persisting State
Zustand allows easy state persistence using middleware:
import { persist } from "zustand/middleware";
const useUserStore = create(
persist(
(set) => ({
user: null,
setUser: (user) => set({ user }),
}),
{
name: "user-storage", // Persisted in localStorage
}
)
);
Now, user
state remains stored across page reloads.
2. Selective State Updates
Zustand lets you subscribe to specific slices of state, preventing unnecessary re-renders:
const count = useStore((state) => state.count); // Only re-renders when count changes
This makes Zustand much more performant compared to React Context.
Conclusion
Zustand simplifies state management with a small API, better performance, and persistence support. It’s an excellent choice for global state management in React without the complexity of Redux.