Zustand
Learn Zustand, a lightweight state management solution for React. This is a foundational concept in component-based UI development that professional developers rely on daily. The explanations below are written to be beginner-friendly while covering the depth and nuance that comes from real-world React experience. Take your time with each section and practice the examples
What is Zustand?
Zustand is a small, fast and scalable state management solution. It has a comfy API based on hooks and isn't boilerplate heavy or opinionated.. This is an essential concept that every React developer must understand thoroughly. In professional development environments, getting this right can mean the difference between code that works reliably and code that breaks in production. The following sections break this down into clear, digestible pieces with practical examples you can try immediately
Basic Zustand Store
// Install Zustand
npm install zustand
// Create a store
import { create } from 'zustand';
const useCounterStore = create((set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
decrement: () => set((state) => ({ count: state.count - 1 })),
reset: () => set({ count: 0 })
}));
// Using the store in components
function Counter() {
const { count, increment, decrement, reset } = useCounterStore();
return (
<div>
<h2>Count: {count}</h2>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
<button onClick={reset}>Reset</button>
</div>
);
}
// Complex store with async actions
const useUserStore = create((set, get) => ({
users: [],
loading: false,
error: null,
fetchUsers: async () => {
set({ loading: true, error: null });
try {
const response = await fetch('/api/users');
const users = await response.json();
set({ users, loading: false });
} catch (error) {
set({ error: error.message, loading: false });
}
},
addUser: async (user) => {
try {
const response = await fetch('/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(user)
});
const newUser = await response.json();
set((state) => ({ users: [...state.users, newUser] }));
} catch (error) {
set({ error: error.message });
}
}
}));Zustand with Persistence
// Store with persistence
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
const useAuthStore = create(
persist(
(set) => ({
user: null,
token: null,
login: (userData, token) => set({ user: userData, token }),
logout: () => set({ user: null, token: null })
}),
{
name: 'auth-storage', // unique name for localStorage key
getStorage: () => localStorage
}
)
);
// Using persisted store
function LoginForm() {
const { login } = useAuthStore();
const handleSubmit = async (e) => {
e.preventDefault();
// Simulate login
const userData = { id: 1, name: 'John Doe' };
const token = 'jwt-token';
login(userData, token);
};
return (
<form onSubmit={handleSubmit}>
<input type="email" placeholder="Email" />
<input type="password" placeholder="Password" />
<button type="submit">Login</button>
</form>
);
}