Loading...
Loading...
Local, global, and server state — Redux, Zustand, React Query, and when to use each.
Local, global, and server state: Redux Toolkit, Zustand, Context API, React Query, MobX, Jotai — patterns, trade-offs, and when to use each.
Local, global, and server state in React: useState, useReducer, Redux Toolkit, Zustand, Context API, React Query, MobX, and Jotai — library comparison, architecture patterns, and clear rules for when to use each.
State management is the backbone of every frontend app — SDE-2 interviews expect you to distinguish local vs global vs server state and pick the right tool without over-engineering.
This module covers useState and useReducer, Redux Toolkit, Zustand, Context API, React Query, MobX, and Jotai — plus single source of truth, immutable updates, selectors, middleware, and architecture patterns.
The goal is to pick the smallest tool that fits: local state for UI, React Query for server data, Zustand or Redux only when multiple distant components genuinely need shared mutable state.
Compare Redux Toolkit, Zustand, Context API, React Query, MobX, and Jotai with bundle size, boilerplate, DevTools, and re-render behavior — plus patterns like selectors, middleware, and optimistic updates.
State management questions appear in nearly every SDE-2 frontend interview. You must explain local vs global vs server state, why Context re-renders all consumers, when Redux beats Zustand, and why React Query belongs with API data — not in Redux. Over-engineering state is a common red flag interviewers watch for.
Controlling, sharing, and updating data across your application.
State Management is the process of controlling, sharing, and updating data across different parts of an application. It ensures apps are responsive, consistent, and scalable.
What is state?
Local, global, and server state — three buckets, three strategies.
A. Local State
State managed within a single component or small group. Use for UI toggles, form inputs, component-specific data.
function Toggle() { const [isOpen, setIsOpen] = useState(false); return ( <button type="button" onClick={() => setIsOpen(!isOpen)}> {isOpen ? "Open" : "Closed"} </button> ); }
Libraries: useState, useReducer (complex local state)
B. Global State
State shared across multiple components or the entire app — auth, theme, cart items.
C. Server State
Data fetched from an external API — not managed locally. Needs caching, deduping, background updates, offline support, pagination.
Golden rule
Deep dive into each tool — pros, cons, and code examples.
Redux Toolkit
Centralized state (Redux pattern)
Pros
Cons
Best for: Large, complex enterprise applications
const store = configureStore({ reducer: { user: userReducer, posts: postsReducer }, }); const user = useSelector((state) => state.user); dispatch(loginAction(userData));
Zustand
Centralized but minimal
Pros
Cons
Best for: Simple to medium apps, quick development
const useStore = create((set) => ({ user: null, setUser: (user) => set({ user }), })); const { user, setUser } = useStore();
Context API
Built-in React
Pros
Cons
Best for: Small apps — theme, simple auth
const UserContext = createContext<User | null>(null); <UserContext.Provider value={user}> {children} </UserContext.Provider> const user = useContext(UserContext);
React Query (TanStack Query)
Server state management
Pros
Cons
Best for: API data fetching — posts, users, products
const { data, isLoading } = useQuery({ queryKey: ["posts"], queryFn: fetchPosts, staleTime: 5 * 60 * 1000, gcTime: 30 * 60 * 1000, });
MobX
Observable-based (reactive)
Pros
Cons
Best for: Apps needing reactive updates
class Store { user: User | null = null; setUser(user: User) { this.user = user; } } makeAutoObservable(this);
Jotai
Atomic state management
Pros
Cons
Best for: Simple global state with atomic granularity
const userAtom = atom<User | null>(null); function User() { const [user, setUser] = useAtom(userAtom); return <div>{user?.name}</div>; }
Side-by-side trade-offs at a glance.
| Library | Type | Pros | Cons | Best For |
|---|---|---|---|---|
| Redux Toolkit | Centralized | Predictable, dev tools | Boilerplate | Large complex apps |
| Zustand | Centralized | Minimal, small bundle | Less structured | Simple/medium apps |
| Context API | Built-in | No external lib | Re-renders all | Small apps, theme |
| React Query | Server state | Caching, deduping | Server only | API data fetching |
| MobX | Observable | Reactive | Less predictable | Reactive updates |
| Jotai | Atomic | Minimal, atomic | Less known | Simple global state |
Single source of truth, immutability, actions, selectors, middleware.
Single Source of Truth
One central store for all state — predictable changes, easy debugging, consistent data across the app.
const store = configureStore({ reducer }); // All state in one place
Immutable Updates
// BAD — mutable state.user.name = "John"; // GOOD — immutable setState({ user: { ...state.user, name: "John" } });
Action-Based Updates
dispatch({ type: "LOGIN", payload: userData });
Clear intent, easy debugging, traceable changes.
Selectors
const user = useSelector((state) => state.user); const userName = useSelector((state) => state.user.name);
Extract specific slices — avoid exposing entire state. Memoize for performance.
Middleware
Interceptors between dispatch and state update — async (thunk, saga), logging, analytics, error handling.
const login = createAsyncThunk("user/login", async (credentials) => { const response = await api.login(credentials); return response.user; });
Optimistic Updates
Update UI before server confirms — instant feedback, rollback on error.
const mutation = useMutation({ mutationFn: updatePost, onMutate: async (newPost) => { await queryClient.cancelQueries({ queryKey: ["post", id] }); queryClient.setQueryData(["post", id], newPost); }, onError: (_err, _vars, context) => { queryClient.setQueryData(["post", id], context?.previous); }, });
Redux, Observable, Atomic, and Server State flows.
Pattern 1 — Redux
Pattern 2 — Observable (MobX)
Pattern 3 — Atomic (Jotai)
Pattern 4 — Server State (React Query)
Match the library to the scenario.
| Scenario | Recommended |
|---|---|
| Simple app, small state | Context API, useState |
| Medium app, some global state | Zustand |
| Large app, complex state | Redux Toolkit |
| API data fetching | React Query |
| Reactive updates | MobX |
| Atomic global state | Jotai |
| GraphQL | Apollo Client |
| Form state | React Hook Form |
Ten points to nail state management questions.
Common interview questions about state management.