Frameworks & Libraries
State Management
Manage how data flows and changes in your application. From built-in React hooks to powerful libraries like Zustand and Redux Toolkit — learn when and why to reach for each approach.
How should I manage state in a JavaScript app?
Keep state as local as possible: component state for UI details, lifted to a shared parent when siblings need it, context for rarely-changing app-wide values (theme, current user), and a store (Zustand, Redux Toolkit) only for complex shared client state. Server data such as API results is best handled by a data-fetching library like TanStack Query.
// Zustand store
import { create } from "zustand";
export const useCart = create((set) => ({
items: [],
add: (item) => set((s) => ({ items: [...s.items, item] })),
}));
// in a component
const items = useCart((s) => s.items);State Categories
Local State
Form inputs
Toggle open/close
Tab selection
Pagination
Animation state
Global UI State
Theme (dark/light)
Language / locale
Sidebar collapsed
Toast notifications
Modal open state
Server State
API response data
Loading/error status
Pagination data
Search results
Real-time updates
Auth / Session
Current user data
Auth tokens
Permissions/roles
Session expiry
OAuth state
Common Pitfalls
Putting everything in global state (e.g. Redux) — creates tight coupling, hard to test, unnecessary re-renders
Default to local state. Lift state up only when needed. Use external store only for truly global data.
Using Context API for high-frequency updates (every keystroke) — causes all consumers to re-render
For high-frequency updates, use Zustand/Jotai with selectors, or React.memo + granular contexts.
Fetching data in useEffect and storing in useState — no caching, no deduplication, complex loading/error states
Use React Query or SWR for server state. They handle caching, refetching, loading, error automatically.
Mutating Redux state directly: state.items.push(item) — breaks time-travel, Redux detects no change
Redux Toolkit uses Immer under the hood — state.items.push(item) is ALLOWED inside createSlice reducers.
Interactive Demo
Code Editor
<button id="add">Add item</button> <button id="reset">Reset</button>
<p>Items: <b id="count">0</b> · Total: <b id="total">$0</b></p>Preview
State Management: summary
Key points
- Derived values (totals, filtered lists) should be computed, not stored as separate state.
- URL state (filters, tabs, pagination) belongs in the query string so it's shareable.
- Server state has caching and staleness concerns that UI state doesn't.
Frequently asked questions
›Do I need Redux?
Most apps don't. Start with component state and context; reach for a store when many distant components share frequently changing state.