🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

React State Management: Context, Zustand, Redux

React ArchitectureStateđŸŸĸ Free Lesson

What You'll Learn

  • 1Classify application state by ownership before selecting any library
  • 2Explain why a large context value re-renders every consumer
  • 3Build a Zustand store that re-renders only the selected slice
  • 4Decide when an action log and reducers justify the weight of Redux Toolkit

Ownership first, library second

Teams usually pick a state library before they have agreed on where their state should live, and the result is a store full of values that belonged to one screen. The cheaper question is never which library, it is who owns this value and who else needs to read it.

State that only one component uses should live in that component, next to the code that changes it. State shared by a parent and its children belongs at the common ancestor. State read by distant parts of the tree but changed rarely, such as the current user or the active theme, belongs in context. State that changes often, is read by many components, and must survive unmounting belongs in a store. State that came from a server belongs in a cache layer rather than in any of those, because duplicating it invites stale copies that never invalidate.

Every library below solves the last case. None of them solve the first four, and applying one there simply moves the problem.

A quick map of the usual situations

SituationSensible choiceNotes
One component toggles its own paneluseStateNo sharing, no ceremony
Two siblings read the same filter textLift state to their parentRemove the duplication instead of adding a tool
Whole tree reads theme, user, localeContext with a stable valueConsumers re-render when the value changes, so keep it small
Many components read one fast-changing sliceZustand, Jotai, or a selector storeSubscribe to a derived value, not the whole object
Actions must be logged, replayed, and dev-inspectedRedux ToolkitThe store itself documents what happened
Server data with refetching and invalidationA query libraryTreat it as a cache, not as component state

Colocation without duplication

Lifting state sounds simple and goes wrong in a predictable way: the parent collects setters it does not use, props thread through intermediate components that ignore them, and unrelated children re-render because a sibling's input changed. The first repair is to push state back down until only the components that read it hold it, then share behaviour rather than values by extracting a custom hook.

function useCart() {
  const [items, setItems] = useState([]);

  const add = (product) =>
    setItems((list) => {
      const existing = list.find((i) => i.id === product.id);
      return existing
        ? list.map((i) => (i.id === product.id ? { ...i, qty: i.qty + 1 } : i))
        : [...list, { ...product, qty: 1 }];
    });

  const remove = (id) => setItems((list) => list.filter((i) => i.id !== id));
  const total = items.reduce((sum, i) => sum + i.price * i.qty, 0);

  return { items, add, remove, total };
}

Two components calling this hook still get two independent carts. That is correct behaviour, not a bug, and it is the reason colocation stays the default: sharing has to be an explicit decision.

Context is dependency injection, not a store

Context passes a value down the tree without prop drilling, and it re-renders every consumer when that value changes. There is no built-in subscription, so a provider holding a large object updates all of them at once, even the components that only read a boolean inside it.

const SessionContext = createContext(null);
const SessionDispatchContext = createContext(null);

function sessionReducer(state, action) {
  switch (action.type) {
    case 'signed-in':
      return { user: action.user, status: 'authenticated' };
    case 'signed-out':
      return { user: null, status: 'anonymous' };
    default:
      return state;
  }
}

function SessionProvider({ children }) {
  const [session, dispatch] = useReducer(sessionReducer, {
    user: null,
    status: 'anonymous',
  });

  return (
    <SessionContext.Provider value={session}>
      <SessionDispatchContext.Provider value={dispatch}>
        {children}
      </SessionDispatchContext.Provider>
    </SessionContext.Provider>
  );
}

function useSession() {
  const value = useContext(SessionContext);
  if (!value) throw new Error('useSession requires SessionProvider');
  return value;
}

Splitting value and dispatch means consumers that only fire actions never re-render when the session object is replaced, because the dispatch reference is stable. It is the smallest change with the largest effect, and it is the standard first fix when a provider sits near the root of a busy application.

Zustand: subscribe to the slice you read

External stores solve the context problem with subscription: a component re-renders only when the value returned by its selector changes. The store lives outside React, so it survives unmounts and can be read from event handlers without any hook at all.

import { create } from 'zustand';

const useShop = create((set, get) => ({
  cart: [],
  add: (item) => set((s) => ({ cart: [...s.cart, item] })),
  clear: () => set({ cart: [] }),
  count: () => get().cart.length,
}));

function CartBadge() {
  const count = useShop((s) => s.cart.length);
  return <span className="badge">{count}</span>;
}

function AddButton({ item }) {
  const add = useShop((s) => s.add);
  return <button type="button" onClick={() => add(item)}>Add to cart</button>;
}

The selector is the whole trick. CartBadge rerenders only when the length changes, so adding an item with a new price but the same count leaves it alone. Returning a freshly built object from a selector without an equality function defeats this and produces a render loop, which is the most common way this library is misused.

Redux Toolkit when traceability matters

Redux asks every change to arrive as a plain action, with reducers describing the transition and middleware observing everything that happens. That structure earns its keep when several teams touch the same flows, when you need to replay a session to reproduce a report, or when dev tooling must explain how a screen reached a surprising value.

Redux Toolkit removes the boilerplate that gave Redux a bad reputation: createSlice generates the action creators and reducers together, configureStore wires the dev tools and serialisability checks, and createAsyncThunk handles request lifecycle states. The mental model remains a single state tree updated by pure functions, which is easy to test because a reducer is just a function of state and action.

If you cannot articulate why you need that log, a selector-based store or plain context will be less code and just as correct.

A migration order that works in practice

Most teams arrive at state tooling by accident, and the migrations that go badly are the ones that change ownership and library at the same time. A safer sequence starts by inventorying what the application currently keeps in component state, in context, and in ad hoc module singletons. Write down who writes each value and who reads it, because the writers usually outnumber the readers by a wide margin.

Second, delete what can be derived. Counts, totals, filtered arrays, and formatted dates are almost never state, and removing them shrinks the surface that needs a permanent home anywhere in the tree. Third, lift what two siblings share to their common parent, and only when that parent becomes a bottleneck in the profiler do you reach for context or a store. Fourth, move server data into a query cache so the store stops being a mirror of a server response that already has a correct owner.

Only after those four steps does a library choice become interesting, and by then the decision is usually obvious: a handful of slow-moving values in context, one or two fast-changing slices in a selector store, and everything else derived or cached. Teams that skip the inventory end up rewriting the same shop cart in three different systems within a year, each one technically correct and none of them the single source of truth. Write the inventory down, even on a whiteboard, because the next feature will otherwise start from the same guesswork.

Common Mistakes

Putting server responses into a global store and refetching them by hand everywhere

Fix: Use a query cache that owns staleness, refetching, and invalidation for you

Wrapping the whole application in one context whose value is a new object every render

Fix: Split value and dispatch, memoise the value, and keep rarely changing data in it

Selecting the entire store object instead of the fields a component renders

Fix: Select the smallest slice, and return primitives or memoised results from the selector

Mirroring the same value in two stores because two features need it

Fix: Pick one owner and let the other read through a selector or a derived accessor

Best Practices

  • Colocate state until a second reader forces you to move it, and then move it only one level
  • Keep context values small, stable, and split by concern so consumers subscribe narrowly
  • Derive totals, counts, and filtered lists during render instead of storing them
  • Treat a store as a source of truth, not a dumping ground for anything global
  • Document the owner of each shared value in a comment next to its declaration

Key Takeaways

  • State should be lifted only as far as its furthest reader, never to the root by habit
  • Context notifies every consumer, so it suits slow-changing values such as user and theme
  • Selector stores re-render only the fields a component actually reads
  • Redux Toolkit buys an auditable action log, which is valuable only when you need the audit
  • Duplicated state always drifts: choose one owner and derive everything else
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert React Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement