State Management
React Context, Zustand, URL state, and server state patterns.
Overview
State management in Next.js considers server and client state.
Key Concepts
- Server State — Data from server components and fetches
- Client State — UI state with Zustand or Context
- URL State — Search params as state
- Form State — React Hook Form or native forms
- Cache State — SWR or React Query for server data
Code Examples
// Zustand store
import { create } from 'zustand';
const useCartStore = create((set) => ({
items: [],
addItem: (item) => set((state) => ({ items: [...state.items, item] })),
removeItem: (id) => set((state) => ({
items: state.items.filter(item => item.id !== id)
})),
clearCart: () => set({ items: [] })
}));
// URL state with search params
'use client';
import { useSearchParams, useRouter } from 'next/navigation';
function FilterControls() {
const searchParams = useSearchParams();
const router = useRouter();
const setFilter = (key, value) => {
const params = new URLSearchParams(searchParams);
params.set(key, value);
router.push(`?${params.toString()}`);
};
return (
<div>
<select onChange={(e) => setFilter('category', e.target.value)}>
<option value="all">All</option>
<option value="electronics">Electronics</option>
</select>
</div>
);
}
// Combined approach
function ProductPage() {
const cart = useCartStore();
const searchParams = useSearchParams();
const category = searchParams.get('category') || 'all';
return (
<div>
<FilterControls />
<ProductList category={category} />
<Cart items={cart.items} />
</div>
);
}
Practice
Build a shopping cart with Zustand, URL filters, and server-side data.