Next.js course ยท Module 9: Integrations and Advanced Features
Next.js with Zustand - Modern state management
In this lesson11
The cart in the Metropolis Quantum store has to be visible in the header, in the product drawer and on the checkout page. Passing it through props across five levels of components quickly turns into a tangle of cables. Server Components fetch data from the server, but purely client-side state, such as a cart, a theme or notifications, needs a shared store. Neo-Bot, the state keeper of the Metropolis, recommends Zustand for this - a minimalist but powerful state management library.
What is Zustand?
Zustand is a modern state management library that offers:
- Minimalist API - simple and intuitive API
- TypeScript-first - full typing support
- No boilerplate - no template code
- SSR-friendly - support for Server-Side Rendering
- DevTools support - integration with Redux DevTools
- Middleware ecosystem - a rich middleware ecosystem
Advantages of Zustand over Redux
- Less code - no actions, reducers or dispatchers
- Better TypeScript - natural type support
- Modular design - easy store splitting
- Performance - automatic re-render optimization
The most important difference: Zustand needs no provider wrapping the app and no reducers. A store is a plain hook that you import wherever you need it.
Installation and basic setup
Installation
Setup always follows the same order: install the package, create the store with create(), define the state and actions, and finally use the hook in a component. We start with the installation:
# Install Zustand
npm install zustand
# For development tools (optional)
npm install @redux-devtools/extensionThe second package is optional. To inspect the state, the Redux DevTools browser extension plus the devtools middleware you will meet shortly are enough.
Basic store
First we describe the shape of the store with the CounterState interface: one count value and three actions. The create function returns a hook, and set merges the object you pass into the state:
// stores/counterStore.ts
import { create } from 'zustand';
interface CounterState {
count: number;
increment: () => void;
decrement: () => void;
reset: () => void;
}
export const useCounterStore = create<CounterState>()((set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
decrement: () => set((state) => ({ count: state.count - 1 })),
reset: () => set({ count: 0 }),
}));Notice the double parentheses create<CounterState>()(...): this is the recommended TypeScript form that lets types be inferred correctly. Actions are plain functions in the same object as the data, with no dispatch at all.
Using it in a component
The useCounterStore hook works only in client components, which is why the file starts with 'use client':
// components/Counter.tsx
'use client';
import { useCounterStore } from '@/stores/counterStore';
export default function Counter() {
const { count, increment, decrement, reset } = useCounterStore();
return (
<div className="bg-white p-6 rounded-lg shadow">
<h2 className="text-2xl font-bold mb-4">Counter: {count}</h2>
<div className="space-x-4">
<button
onClick={increment}
className="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600"
>
+1
</button>
<button
onClick={decrement}
className="bg-red-500 text-white px-4 py-2 rounded hover:bg-red-600"
>
-1
</button>
<button
onClick={reset}
className="bg-gray-500 text-white px-4 py-2 rounded hover:bg-gray-600"
>
Reset
</button>
</div>
</div>
);
}The counter works without any provider in the tree. This form reads the whole store, though, so the component re-renders on every change, and in the performance section you will see how selectors fix that.
Advanced patterns
User store with authentication
A real store also keeps loading state and errors. The persist middleware saves a chosen part of the state to localStorage, and get lets you read the state inside an action:
// stores/userStore.ts
import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
interface User {
id: string;
name: string;
email: string;
avatar?: string;
role: 'user' | 'admin';
}
interface UserState {
user: User | null;
isLoading: boolean;
error: string | null;
login: (email: string, password: string) => Promise<void>;
logout: () => void;
updateProfile: (data: Partial<User>) => Promise<void>;
setUser: (user: User) => void;
clearError: () => void;
}
export const useUserStore = create<UserState>()(
persist(
(set, get) => ({
user: null,
isLoading: false,
error: null,
login: async (email: string, password: string) => {
set({ isLoading: true, error: null });
try {
const response = await fetch('/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password }),
});
if (!response.ok) {
throw new Error('Invalid login credentials');
}
const userData = await response.json();
set({ user: userData.user, isLoading: false });
} catch (error) {
set({
error: error instanceof Error ? error.message : 'An error occurred',
isLoading: false
});
}
},
logout: () => {
set({ user: null, error: null });
// Call logout API
fetch('/api/auth/logout', { method: 'POST' });
},
updateProfile: async (data: Partial<User>) => {
const { user } = get();
if (!user) return;
set({ isLoading: true });
try {
const response = await fetch('/api/user/profile', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
});
if (!response.ok) {
throw new Error('Failed to update profile');
}
const updatedUser = await response.json();
set({ user: updatedUser, isLoading: false });
} catch (error) {
set({
error: error instanceof Error ? error.message : 'An error occurred',
isLoading: false
});
}
},
setUser: (user: User) => set({ user }),
clearError: () => set({ error: null }),
}),
{
name: 'user-storage',
storage: createJSONStorage(() => localStorage),
partialize: (state) => ({ user: state.user }), // Persist only user data
}
)
);Async actions are just async functions, so Zustand needs no thunk-style middleware. The partialize option saves only user, without the loading and error flags. Watch out for SSR: the server cannot see localStorage, so state restored on the client may differ from the server HTML.
Shopping cart store
The cart shows how to change arrays without mutating them. The type Omit<CartItem, 'quantity'> means a product without the quantity field, because the store sets the quantity:
// stores/cartStore.ts
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
interface CartItem {
id: string;
name: string;
price: number;
quantity: number;
image?: string;
variant?: {
size?: string;
color?: string;
};
}
interface CartState {
items: CartItem[];
isOpen: boolean;
addItem: (item: Omit<CartItem, 'quantity'>) => void;
removeItem: (id: string) => void;
updateQuantity: (id: string, quantity: number) => void;
clearCart: () => void;
toggleCart: () => void;
getTotalItems: () => number;
getTotalPrice: () => number;
}
export const useCartStore = create<CartState>()(
persist(
(set, get) => ({
items: [],
isOpen: false,
addItem: (newItem) => {
const { items } = get();
const existingItem = items.find(item =>
item.id === newItem.id &&
JSON.stringify(item.variant) === JSON.stringify(newItem.variant)
);
if (existingItem) {
set({
items: items.map(item =>
item === existingItem
? { ...item, quantity: item.quantity + 1 }
: item
),
});
} else {
set({
items: [...items, { ...newItem, quantity: 1 }],
});
}
},
removeItem: (id) => {
set({
items: get().items.filter(item => item.id !== id),
});
},
updateQuantity: (id, quantity) => {
if (quantity <= 0) {
get().removeItem(id);
return;
}
set({
items: get().items.map(item =>
item.id === id ? { ...item, quantity } : item
),
});
},
clearCart: () => set({ items: [] }),
toggleCart: () => set({ isOpen: !get().isOpen }),
getTotalItems: () => {
return get().items.reduce((total, item) => total + item.quantity, 0);
},
getTotalPrice: () => {
return get().items.reduce(
(total, item) => total + item.price * item.quantity,
0
);
},
}),
{
name: 'cart-storage',
}
)
);addItem increases the quantity if the product in the same variant is already in the cart, and otherwise adds a new line. The original array never changes: map and filter always create a new one, which is how React detects the change.
Middleware and DevTools
Redux DevTools integration
Zustand's built-in middleware include devtools, persist, immer, subscribeWithSelector, combine and redux. devtools shows every state change in the Redux DevTools extension:
// stores/appStore.ts
import { create } from 'zustand';
import { devtools } from 'zustand/middleware';
interface AppState {
theme: 'light' | 'dark';
sidebarOpen: boolean;
notifications: Array<{
id: string;
type: 'info' | 'success' | 'warning' | 'error';
message: string;
timestamp: number;
}>;
toggleTheme: () => void;
toggleSidebar: () => void;
addNotification: (notification: Omit<AppState['notifications'][0], 'id' | 'timestamp'>) => void;
removeNotification: (id: string) => void;
}
export const useAppStore = create<AppState>()(
devtools(
(set, get) => ({
theme: 'light',
sidebarOpen: false,
notifications: [],
toggleTheme: () => {
const newTheme = get().theme === 'light' ? 'dark' : 'light';
set({ theme: newTheme });
// Update document class
if (typeof window !== 'undefined') {
document.documentElement.classList.toggle('dark', newTheme === 'dark');
}
},
toggleSidebar: () => set({ sidebarOpen: !get().sidebarOpen }),
addNotification: (notification) => {
const id = Math.random().toString(36).substring(2);
const timestamp = Date.now();
set({
notifications: [
...get().notifications,
{ ...notification, id, timestamp }
]
});
// Auto remove after 5 seconds
setTimeout(() => {
get().removeNotification(id);
}, 5000);
},
removeNotification: (id) => {
set({
notifications: get().notifications.filter(n => n.id !== id)
});
},
}),
{
name: 'app-store',
}
)
);The theme, the sidebar and the notifications live in a single app store. A notification disappears by itself after 5 seconds, and typeof window keeps the code from running on the server.
Immer middleware for immutable updates
The immer middleware lets you write changes as if you were mutating the state. It needs a separate package:
npm install immerNow state.todos.push(...) inside set is safe, because Immer creates a new copy behind the scenes:
// stores/todosStore.ts
import { create } from 'zustand';
import { immer } from 'zustand/middleware/immer';
interface Todo {
id: string;
text: string;
completed: boolean;
priority: 'low' | 'medium' | 'high';
dueDate?: Date;
}
interface TodosState {
todos: Todo[];
filter: 'all' | 'active' | 'completed';
addTodo: (text: string, priority?: Todo['priority']) => void;
toggleTodo: (id: string) => void;
deleteTodo: (id: string) => void;
editTodo: (id: string, text: string) => void;
setFilter: (filter: TodosState['filter']) => void;
clearCompleted: () => void;
}
export const useTodosStore = create<TodosState>()(
immer((set) => ({
todos: [],
filter: 'all',
addTodo: (text, priority = 'medium') =>
set((state) => {
state.todos.push({
id: Math.random().toString(36).substring(2),
text,
completed: false,
priority,
});
}),
toggleTodo: (id) =>
set((state) => {
const todo = state.todos.find((t) => t.id === id);
if (todo) {
todo.completed = !todo.completed;
}
}),
deleteTodo: (id) =>
set((state) => {
state.todos = state.todos.filter((t) => t.id !== id);
}),
editTodo: (id, text) =>
set((state) => {
const todo = state.todos.find((t) => t.id === id);
if (todo) {
todo.text = text;
}
}),
setFilter: (filter) =>
set((state) => {
state.filter = filter;
}),
clearCompleted: () =>
set((state) => {
state.todos = state.todos.filter((t) => !t.completed);
}),
}))
);Compare toggleTodo with a version without Immer: instead of mapping the whole array you change one field. From the outside nothing changes, components still receive immutable state.
SSR and hydration
Store provider for SSR
A store created at module level is shared by all requests on the server, so one user's data could leak to another. The Zustand docs recommend a separate store per request in Next.js, passed through React Context:
// providers/StoreProvider.tsx
'use client';
import { type ReactNode, createContext, useRef, useContext } from 'react';
import { useStore } from 'zustand';
import { type UserStore, createUserStore, initUserStore } from '@/stores/userStore';
export type UserStoreApi = ReturnType<typeof createUserStore>;
export const UserStoreContext = createContext<UserStoreApi | undefined>(undefined);
export interface UserStoreProviderProps {
children: ReactNode;
initialState?: Parameters<typeof initUserStore>[0];
}
export const UserStoreProvider = ({ children, initialState }: UserStoreProviderProps) => {
const storeRef = useRef<UserStoreApi | null>(null);
if (!storeRef.current) {
storeRef.current = createUserStore(initUserStore(initialState));
}
return (
<UserStoreContext.Provider value={storeRef.current}>
{children}
</UserStoreContext.Provider>
);
};
export const useUserStore = <T,>(selector: (store: UserStore) => T): T => {
const userStoreContext = useContext(UserStoreContext);
if (!userStoreContext) {
throw new Error('useUserStore must be used within UserStoreProvider');
}
return useStore(userStoreContext, selector);
};useRef guarantees that the store is created only once per provider instance. In React 19 useRef requires an initial value, hence null. The useStore hook from the zustand package reads the selected slice of the store from context.
Updated store definition
We now create the store itself with createStore from zustand/vanilla, which returns a store object instead of a hook:
// stores/userStore.ts (updated for SSR)
import { createStore } from 'zustand/vanilla';
export interface UserStore {
user: User | null;
isLoading: boolean;
login: (email: string, password: string) => Promise<void>;
logout: () => void;
}
export const initUserStore = (initialState?: Partial<UserStore>): UserStore => {
return {
user: null,
isLoading: false,
login: async (email: string, password: string) => {
// Implementation
},
logout: () => {
// Implementation
},
...initialState,
};
};
export const createUserStore = (initialState: UserStore) => {
return createStore<UserStore>()(() => initialState);
};initUserStore builds the initial state and createUserStore creates the store. The action logic did not change, only the place where the store is created.
Components with Zustand
Theme toggle component
The theme toggle reads state and an action from the app store:
// components/ThemeToggle.tsx
'use client';
import { useAppStore } from '@/stores/appStore';
import { Moon, Sun } from 'lucide-react';
export default function ThemeToggle() {
const { theme, toggleTheme } = useAppStore();
return (
<button
onClick={toggleTheme}
className="p-2 rounded-lg bg-gray-200 dark:bg-gray-800 hover:bg-gray-300 dark:hover:bg-gray-700 transition-colors"
aria-label="Toggle theme"
>
{theme === 'light' ? (
<Moon className="w-5 h-5" />
) : (
<Sun className="w-5 h-5" />
)}
</button>
);
}The component knows nothing about document or the dark class, the store holds all the logic.
Shopping cart drawer
The cart drawer is a bigger component that uses every cart action:
// components/CartDrawer.tsx
'use client';
import { useCartStore } from '@/stores/cartStore';
import { X, Plus, Minus, Trash2 } from 'lucide-react';
export default function CartDrawer() {
const {
items,
isOpen,
toggleCart,
updateQuantity,
removeItem,
getTotalPrice,
getTotalItems,
} = useCartStore();
if (!isOpen) return null;
return (
<div className="fixed inset-0 z-50">
{/* Overlay */}
<div
className="absolute inset-0 bg-black/50"
onClick={toggleCart}
/>
{/* Drawer */}
<div className="absolute right-0 top-0 h-full w-96 bg-white shadow-xl">
<div className="flex items-center justify-between p-4 border-b">
<h2 className="text-lg font-semibold">
Cart ({getTotalItems()})
</h2>
<button
onClick={toggleCart}
className="p-2 hover:bg-gray-100 rounded"
>
<X className="w-5 h-5" />
</button>
</div>
<div className="flex-1 overflow-y-auto p-4">
{items.length === 0 ? (
<p className="text-gray-500 text-center mt-8">
Your cart is empty
</p>
) : (
<div className="space-y-4">
{items.map((item) => (
<div key={item.id} className="flex items-center space-x-4 p-4 border rounded">
{item.image && (
<img
src={item.image}
alt={item.name}
className="w-16 h-16 object-cover rounded"
/>
)}
<div className="flex-1">
<h3 className="font-medium">{item.name}</h3>
<p className="text-gray-600">{item.price} USD</p>
{item.variant && (
<p className="text-sm text-gray-500">
{item.variant.size && `Size: ${item.variant.size}`}
{item.variant.color && ` Color: ${item.variant.color}`}
</p>
)}
</div>
<div className="flex items-center space-x-2">
<button
onClick={() => updateQuantity(item.id, item.quantity - 1)}
className="p-1 hover:bg-gray-100 rounded"
>
<Minus className="w-4 h-4" />
</button>
<span className="w-8 text-center">{item.quantity}</span>
<button
onClick={() => updateQuantity(item.id, item.quantity + 1)}
className="p-1 hover:bg-gray-100 rounded"
>
<Plus className="w-4 h-4" />
</button>
<button
onClick={() => removeItem(item.id)}
className="p-1 hover:bg-red-100 text-red-600 rounded"
>
<Trash2 className="w-4 h-4" />
</button>
</div>
</div>
))}
</div>
)}
</div>
{items.length > 0 && (
<div className="border-t p-4">
<div className="flex justify-between mb-4">
<span className="font-semibold">Total:</span>
<span className="font-semibold">{getTotalPrice()} USD</span>
</div>
<button className="w-full bg-blue-600 text-white py-3 rounded-lg hover:bg-blue-700 transition-colors">
Go to checkout
</button>
</div>
)}
</div>
</div>
);
}The plus and minus buttons call updateQuantity, and going down to zero removes the line, because that is how we defined the action in the store. The component computes nothing itself, the totals come from getTotalItems and getTotalPrice.
Notifications component
The notification list renders a separate NotificationItem component for each entry:
// components/Notifications.tsx
'use client';
import { useEffect } from 'react';
import { useAppStore } from '@/stores/appStore';
import { X, CheckCircle, AlertCircle, Info, AlertTriangle } from 'lucide-react';
export default function Notifications() {
const { notifications, removeNotification } = useAppStore();
return (
<div className="fixed top-4 right-4 z-50 space-y-2">
{notifications.map((notification) => (
<NotificationItem
key={notification.id}
notification={notification}
onRemove={() => removeNotification(notification.id)}
/>
))}
</div>
);
}
interface NotificationItemProps {
notification: {
id: string;
type: 'info' | 'success' | 'warning' | 'error';
message: string;
timestamp: number;
};
onRemove: () => void;
}
function NotificationItem({ notification, onRemove }: NotificationItemProps) {
const { type, message } = notification;
const icons = {
info: Info,
success: CheckCircle,
warning: AlertTriangle,
error: AlertCircle,
};
const colors = {
info: 'bg-blue-50 border-blue-200 text-blue-800',
success: 'bg-green-50 border-green-200 text-green-800',
warning: 'bg-yellow-50 border-yellow-200 text-yellow-800',
error: 'bg-red-50 border-red-200 text-red-800',
};
const Icon = icons[type];
useEffect(() => {
const timer = setTimeout(onRemove, 5000);
return () => clearTimeout(timer);
}, [onRemove]);
return (
<div className={`flex items-center p-4 border rounded-lg shadow-lg ${colors[type]} min-w-80 max-w-md`}>
<Icon className="w-5 h-5 mr-3 shrink-0" />
<div className="flex-1">
<p className="text-sm font-medium">{message}</p>
</div>
<button
onClick={onRemove}
className="ml-3 shrink-0 p-1 hover:bg-white hover:bg-white/20 rounded"
>
<X className="w-4 h-4" />
</button>
</div>
);
}Icons and colors are plain objects picked by notification type. The store already removes a notification after 5 seconds, so the timer in the component is an extra safety net.
API integration
API client with Zustand
An HTTP client can read the state outside React through getState(), without a hook:
// lib/api-client.ts
import { useUserStore } from '@/stores/userStore';
class ApiClient {
private baseURL: string;
constructor(baseURL: string) {
this.baseURL = baseURL;
}
private async request<T>(
endpoint: string,
options: RequestInit = {}
): Promise<T> {
const { user } = useUserStore.getState();
const config: RequestInit = {
headers: {
'Content-Type': 'application/json',
...(user && { Authorization: `Bearer ${user.token}` }),
...options.headers,
},
...options,
};
const response = await fetch(`${this.baseURL}${endpoint}`, config);
if (!response.ok) {
throw new Error(`API Error: ${response.status}`);
}
return response.json();
}
get<T>(endpoint: string): Promise<T> {
return this.request<T>(endpoint);
}
post<T>(endpoint: string, data: any): Promise<T> {
return this.request<T>(endpoint, {
method: 'POST',
body: JSON.stringify(data),
});
}
put<T>(endpoint: string, data: any): Promise<T> {
return this.request<T>(endpoint, {
method: 'PUT',
body: JSON.stringify(data),
});
}
delete<T>(endpoint: string): Promise<T> {
return this.request<T>(endpoint, {
method: 'DELETE',
});
}
}
export const apiClient = new ApiClient(process.env.NEXT_PUBLIC_API_URL || '');Every request gets an authorization header when the user is logged in. In a real project the User type then needs a token field.
Products store with an API
The products store combines data fetching, search and filtering:
// stores/productsStore.ts
import { create } from 'zustand';
import { apiClient } from '@/lib/api-client';
interface Product {
id: string;
name: string;
price: number;
description: string;
images: string[];
category: string;
inStock: boolean;
}
interface ProductsState {
products: Product[];
loading: boolean;
error: string | null;
searchQuery: string;
selectedCategory: string | null;
fetchProducts: () => Promise<void>;
searchProducts: (query: string) => void;
filterByCategory: (category: string | null) => void;
getFilteredProducts: () => Product[];
}
export const useProductsStore = create<ProductsState>()((set, get) => ({
products: [],
loading: false,
error: null,
searchQuery: '',
selectedCategory: null,
fetchProducts: async () => {
set({ loading: true, error: null });
try {
const products = await apiClient.get<Product[]>('/products');
set({ products, loading: false });
} catch (error) {
set({
error: error instanceof Error ? error.message : 'Failed to fetch products',
loading: false,
});
}
},
searchProducts: (query: string) => {
set({ searchQuery: query });
},
filterByCategory: (category: string | null) => {
set({ selectedCategory: category });
},
getFilteredProducts: () => {
const { products, searchQuery, selectedCategory } = get();
return products.filter((product) => {
const matchesSearch = searchQuery === '' ||
product.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
product.description.toLowerCase().includes(searchQuery.toLowerCase());
const matchesCategory = selectedCategory === null ||
product.category === selectedCategory;
return matchesSearch && matchesCategory;
});
},
}));getFilteredProducts derives the result from the current state instead of keeping a second copy of the list. In Next.js, though, initial data is better fetched in a Server Component, keeping only UI state, like the search phrase, in Zustand.
Performance optimization
Selectors for optimization
A selector picks only the needed slice of the store, so the component re-renders only when that slice changes. When a selector returns a new object, wrap it in useShallow:
// hooks/useOptimizedSelectors.ts
import { useShallow } from 'zustand/react/shallow';
import { useCartStore } from '@/stores/cartStore';
// Good - use selectors
export const useCartInfo = () => {
return useCartStore(
useShallow((state) => ({
totalItems: state.getTotalItems(),
totalPrice: state.getTotalPrice(),
itemsCount: state.items.length,
}))
);
};
// Good - single values
export const useCartIsOpen = () => useCartStore((state) => state.isOpen);
// Bad - the entire store
// export const useEntireStore = () => useCartStore();Without useShallow every render would create a new object, and Zustand 5 would treat it as a change. A single value, such as isOpen, does not need this safeguard.
Subscription pattern
The subscribe method calls a function on every state change, outside the render cycle. It receives the new and the previous state:
// hooks/useStoreSubscription.ts
import { useEffect } from 'react';
import { useCartStore } from '@/stores/cartStore';
export const useCartAnalytics = () => {
useEffect(() => {
const unsubscribe = useCartStore.subscribe(
(state, prevState) => {
const items = state.items;
const prevItems = prevState.items;
// Track analytics when cart changes
if (items.length > prevItems.length) {
// Item added
console.log('Item added to cart');
} else if (items.length < prevItems.length) {
// Item removed
console.log('Item removed from cart');
}
}
);
return unsubscribe;
}, []);
};The hook compares the list length before and after the change, and the function returned by subscribe cleans up the subscription. The variant with a separate selector as the first argument requires the subscribeWithSelector middleware.
Testing
Store testing
A store is a plain hook, so you test it with renderHook from Testing Library, and setState resets the state before each test:
// __tests__/stores/counterStore.test.ts
import { renderHook, act } from '@testing-library/react';
import { useCounterStore } from '@/stores/counterStore';
describe('Counter Store', () => {
beforeEach(() => {
useCounterStore.setState({ count: 0 });
});
it('should increment count', () => {
const { result } = renderHook(() => useCounterStore());
act(() => {
result.current.increment();
});
expect(result.current.count).toBe(1);
});
it('should decrement count', () => {
const { result } = renderHook(() => useCounterStore());
act(() => {
result.current.increment();
result.current.decrement();
});
expect(result.current.count).toBe(0);
});
it('should reset count', () => {
const { result } = renderHook(() => useCounterStore());
act(() => {
result.current.increment();
result.current.increment();
result.current.reset();
});
expect(result.current.count).toBe(0);
});
});Every test starts from zero thanks to beforeEach, so results do not leak between tests.
Best practices
1. Store organization
Split state by topic instead of building one store for everything:
// Good - split stores by topic
// stores/
// โโโ userStore.ts // User authentication & profile
// โโโ cartStore.ts // Shopping cart
// โโโ productsStore.ts // Products catalog
// โโโ appStore.ts // Global app state
// Bad - one giant store
// stores/globalStore.ts // Everything in one placeSmall stores are easier to test, and no component subscribes to data it does not use.
2. TypeScript best practices
Write the state interface before the implementation and pass the type as a generic:
// Good - define interfaces
interface UserState {
user: User | null;
login: (email: string, password: string) => Promise<void>;
}
// Good - use generic types
export const useUserStore = create<UserState>()((set) => ({
//
}));This way TypeScript checks every action and every field.
3. Error handling
Every async action should set loading and store the error in the state:
// Good - handle errors in the store
const fetchData = async () => {
set({ loading: true, error: null });
try {
const data = await api.fetchData();
set({ data, loading: false });
} catch (error) {
set({
error: error instanceof Error ? error.message : 'Unknown error',
loading: false
});
}
};The component only reads error and loading, it needs no try/catch of its own.
Summary
Zustand with Next.js is a powerful combination for managing application state:
- Minimalist API - simple and readable
- TypeScript-first - full type support
- SSR-friendly - works with Server-Side Rendering
- Performance - automatic optimizations
- Middleware - a rich ecosystem of extensions
My advice: fetch server data in Server Components, keep Zustand for UI state, and always read it through selectors. In the next lesson you will learn advanced Server Actions patterns that save data on the server.
Remember: Zustand is the lightweight state store of the Metropolis, a single hook with no provider and no Redux boilerplate.
Code for this lesson: App.tsx
import React, { useState, useCallback } from 'react';
// Simulated Zustand-like store (Sandpack doesn't support zustand package)
function createStore<T>(initialState: T) {
let state = initialState;
const listeners = new Set<() => void>();
return {
getState: () => state,
setState: (partial: Partial<T> | ((s: T) => Partial<T>)) => {
const nextPartial = typeof partial === 'function' ? partial(state) : partial;
state = { ...state, ...nextPartial };
listeners.forEach(l => l());
},
subscribe: (listener: () => void) => {
listeners.add(listener);
return () => listeners.delete(listener);
},
};
}
interface Task {
id: number;
title: string;
completed: boolean;
priority: 'low' | 'medium' | 'high';
}
interface TodoState {
tasks: Task[];
filter: 'all' | 'active' | 'completed';
}
const store = createStore<TodoState>({
tasks: [
{ id: 1, title: 'Configure Zustand store', completed: true, priority: 'high' },
{ id: 2, title: 'Add middleware (devtools, persist)', completed: false, priority: 'medium' },
{ id: 3, title: 'Implement SSR hydration', completed: false, priority: 'high' },
{ id: 4, title: 'Write unit tests', completed: false, priority: 'low' },
],
filter: 'all',
});
function useStore<R>(selector: (s: TodoState) => R): R {
const [, forceUpdate] = useState(0);
React.useEffect(() => {
return store.subscribe(() => forceUpdate(c => c + 1));
}, []);
return selector(store.getState());
}
const priorityColors = { high: '#f44336', medium: '#ff9800', low: '#4caf50' };
const ZustandDemo = () => {
const tasks = useStore(s => s.tasks);
const filter = useStore(s => s.filter);
const [newTask, setNewTask] = useState('');
const [newPriority, setNewPriority] = useState<Task['priority']>('medium');
const [showCode, setShowCode] = useState(false);
const filteredTasks = tasks.filter(t => {
if (filter === 'active') return !t.completed;
if (filter === 'completed') return t.completed;
return true;
});
const addTask = () => {
if (!newTask.trim()) return;
store.setState(s => ({
tasks: [...s.tasks, { id: Date.now(), title: newTask, completed: false, priority: newPriority }]
}));
setNewTask('');
};
const toggleTask = (id: number) => {
store.setState(s => ({
tasks: s.tasks.map(t => t.id === id ? { ...t, completed: !t.completed } : t)
}));
};
const removeTask = (id: number) => {
store.setState(s => ({ tasks: s.tasks.filter(t => t.id !== id) }));
};
const setFilter = (f: TodoState['filter']) => store.setState({ filter: f });
const stats = {
total: tasks.length,
completed: tasks.filter(t => t.completed).length,
active: tasks.filter(t => !t.completed).length,
};
return (
<div style={{ background: '#0f0f23', minHeight: '100vh', padding: '20px', color: '#fff', fontFamily: 'sans-serif' }}>
<h1 style={{ color: '#64ffda', textAlign: 'center' }}>Next.js + Zustand</h1>
<p style={{ textAlign: 'center', color: '#888', marginBottom: '20px' }}>Lightweight state management</p>
<div style={{ maxWidth: '600px', margin: '0 auto' }}>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '10px', marginBottom: '16px' }}>
{[
{ label: 'Total', value: stats.total, color: '#7c4dff' },
{ label: 'Active', value: stats.active, color: '#ff9800' },
{ label: 'Done', value: stats.completed, color: '#4caf50' },
].map(s => (
<div key={s.label} style={{ background: 'rgba(255,255,255,0.05)', padding: '16px', borderRadius: '8px', textAlign: 'center' }}>
<div style={{ color: s.color, fontSize: '24px', fontWeight: 'bold' }}>{s.value}</div>
<div style={{ color: '#888', fontSize: '12px' }}>{s.label}</div>
</div>
))}
</div>
<div style={{ display: 'flex', gap: '8px', marginBottom: '16px' }}>
<input value={newTask} onChange={e => setNewTask(e.target.value)} placeholder="New task..."
onKeyDown={e => e.key === 'Enter' && addTask()}
style={{ flex: 1, padding: '10px', background: '#16213e', border: '1px solid #444', borderRadius: '6px', color: '#fff' }} />
<select value={newPriority} onChange={e => setNewPriority(e.target.value as Task['priority'])}
style={{ padding: '10px', background: '#16213e', border: '1px solid #444', borderRadius: '6px', color: '#fff' }}>
<option value="high">High</option>
<option value="medium">Medium</option>
<option value="low">Low</option>
</select>
<button onClick={addTask} style={{ padding: '10px 16px', background: '#7c4dff', border: 'none', borderRadius: '6px', color: '#fff', cursor: 'pointer' }}>Add</button>
</div>
<div style={{ display: 'flex', gap: '6px', marginBottom: '12px' }}>
{(['all', 'active', 'completed'] as const).map(f => (
<button key={f} onClick={() => setFilter(f)}
style={{ padding: '6px 14px', background: filter === f ? '#7c4dff' : 'rgba(255,255,255,0.1)', border: 'none', borderRadius: '4px', color: '#fff', cursor: 'pointer', fontSize: '12px' }}>
{f.charAt(0).toUpperCase() + f.slice(1)}
</button>
))}
</div>
<div style={{ background: 'rgba(255,255,255,0.05)', borderRadius: '10px', overflow: 'hidden' }}>
{filteredTasks.map(task => (
<div key={task.id} style={{ display: 'flex', alignItems: 'center', gap: '10px', padding: '12px 16px', borderBottom: '1px solid #1a1a2e' }}>
<input type="checkbox" checked={task.completed} onChange={() => toggleTask(task.id)} />
<span style={{ width: '8px', height: '8px', borderRadius: '50%', background: priorityColors[task.priority] }} />
<span style={{ flex: 1, textDecoration: task.completed ? 'line-through' : 'none', color: task.completed ? '#555' : '#fff' }}>{task.title}</span>
<button onClick={() => removeTask(task.id)} style={{ background: 'none', border: 'none', color: '#f44336', cursor: 'pointer', fontSize: '16px' }}>x</button>
</div>
))}
{filteredTasks.length === 0 && <p style={{ textAlign: 'center', color: '#555', padding: '20px' }}>No tasks</p>}
</div>
</div>
</div>
);
};
export default ZustandDemo;Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. Zustand is a library for:
2. Which of the following is NOT a built-in Zustand middleware?
These are 2 of 3 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Code editor
Create a Zustand store for managing shopping cart state
- Code editor
Implement a store with actions and selectors.
- Click in order
Arrange the steps of configuring a Zustand store in a Next.js application in order.