State Management
Context API, Zustand, Redux Toolkit, Jotai, and state management strategies.
Overview
Choosing the right state management solution depends on app complexity and team preferences.
Key Concepts
- Context API — Built-in solution for lightweight global state
- Zustand — Minimal, fast state management with hooks
- Redux Toolkit — Official Redux recommendation with modern patterns
- Jotai — Atomic state management for fine-grained updates
- State Colocation — Keep state as close to where it's used as possible
Code Examples
// Zustand example
import { create } from 'zustand';
const useStore = create((set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
decrement: () => set((state) => ({ count: state.count - 1 })),
reset: () => set({ count: 0 }),
}));
function Counter() {
const { count, increment, decrement, reset } = useStore();
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>+</button>
<button onClick={decrement}>-</button>
<button onClick={reset}>Reset</button>
</div>
);
}
Practice
Implement a shopping cart with Zustand that tracks items, quantities, and total price.