Suleman Ahmed - BlogModern State Management with Zustand: Simple, Fast, and Scalable

State management is a central topic in React development. While context is great for simple themes, complex applications often require a global store. Zustand has emerged as the developer-favorite alternative to Redux.
Why Choose Zustand?
Zustand is a tiny (less than 1KB) state management library. It uses React hooks, does not require wrapping your app in providers, and prevents unnecessary re-renders through state selection.
Creating a Global Store
Let's define a simple store that handles a shopping cart:
import { create } from 'zustand';
interface CartItem {
id: string;
name: string;
price: number;
quantity: number;
}
interface CartState {
items: CartItem[];
addItem: (item: Omit<CartItem, 'quantity'>) => void;
removeItem: (id: string) => void;
clearCart: () => void;
}
export const useCartStore = create<CartState>((set) => ({
items: [],
addItem: (newItem) =>
set((state) => {
const existing = state.items.find((item) => item.id === newItem.id);
if (existing) {
return {
items: state.items.map((item) =>
item.id === newItem.id ? { ...item, quantity: item.quantity + 1 } : item
),
};
}
return { items: [...state.items, { ...newItem, quantity: 1 }] };
}),
removeItem: (id) =>
set((state) => ({
items: state.items.filter((item) => item.id !== id),
})),
clearCart: () => set({ items: [] }),
}));Using the Store in Components
Using the Zustand hook in React components is highly intuitive:
import { useCartStore } from './cartStore';
export default function CartIndicator() {
// Only re-renders if items.length changes
const itemCount = useCartStore((state) => state.items.length);
const clearCart = useCartStore((state) => state.clearCart);
return (
<div className="flex gap-4 items-center">
<span>Cart items: {itemCount}</span>
<button onClick={clearCart} className="bg-red-500 text-white px-2 py-1 rounded">
Clear
</button>
</div>
);
}With Zustand, state management is simplified back to standard JS actions and objects, keeping performance fast and code concise.
More Articles

A Guide to Effective Unit Testing with Vitest and React Testing Library
Learn how to write reliable tests for your React components. Covers API mocking, event simulations, and clean assertions.

Tailwind CSS v4: The Future of Utility-First CSS
Explore the key improvements in Tailwind CSS v4, featuring native CSS variables, a highly optimized CSS compiler, and simplified config files.

React 19 Server Components: What You Need to Know
Get ready for React 19. Understand how Server Components differ from Client Components, and how they improve page load performance.