Skip to content
FrontDepth, Home

React & Rendering

State management and external stores

Where each piece of state belongs and why: local, shared, server, URL and form state, derived values, lifting state, context and its re-render cost, reducers, external stores with useSyncExternalStore, tearing, selectors and server-state caches.

JuniorMiddleSeniorUpdated 16 November 2026

Reading level

Shows sections up to the selected level.

This topic starts at Junior level.

JuniorConcept

Kinds of state and where each belongs

"State management" is often discussed as a choice of library. The first question is a different one: what kind of state is this? Each kind has different needs and a natural home.

KindExamplesNatural home
Local UI statean open dropdown, the active tab, a draft commentuseState in the component that uses it
Shared client statethe cart, the theme, the signed-in userthe closest common parent; context or an external store when many distant components read it
Server stateproducts, orders, the user's profile from the APIa server-state cache (TanStack Query, SWR, the framework's data loading)
URL statefilters, sort order, page number, a selected tab you want to sharethe URL: route and search params
Form statefield values, touched fields, validation errorsthe form itself, or a form library for complex forms

Why the difference matters:

  • Server state is not yours. It lives on a server, can be changed by other people and goes out of date. It needs caching, refetching and invalidation, not just a variable.
  • URL state must survive a reload, work with the Back button and be shareable as a link. Kept in useState, a filter disappears on refresh.
  • Form state is short-lived. Often uncontrolled inputs plus FormData on submit are enough; nothing outside the form needs every keystroke.
  • Local UI state should die with its component. Put it in a global store, and it outlives the screen, leaks between pages and makes every change global.

One page usually holds several kinds at once:

JSX
function ProductsPage() {
  const [searchParams, setSearchParams] = useSearchParams();
  const sort = searchParams.get("sort") ?? "popular";

  const { data: products = [] } = useQuery({
    queryKey: ["products", { sort }],
    queryFn: () => fetchProducts({ sort }),
  });

  const [isFilterOpen, setFilterOpen] = useState(false);
  const addToCart = useCartStore((state) => state.add);

  // ...
}

The sort order lives in the URL (here React Router's useSearchParams), the product list in a query cache, the panel's open state in local state, and the cart in a shared store.

Start local

A good default: keep state in the component that uses it. Move it up only when another component needs it, and out of React only when many distant components need it or when it changes outside React. Moving state later is a small refactor; untangling a global store that holds everything is a large one.

JuniorExample

Derived state instead of duplicated state

react.dev's "Choosing the State Structure" gives five principles: group related state, avoid contradictions, avoid redundant state, avoid duplication, avoid deep nesting. Most real bugs come from the middle three: two pieces of state that are supposed to agree, and one day don't.

Compute it, don't store it

JSX
function TodoList({ todos }) {
  const [filter, setFilter] = useState("all");
  const [visibleTodos, setVisibleTodos] = useState(todos);

  useEffect(() => {
    setVisibleTodos(todos.filter((todo) => filter === "all" || todo.done === (filter === "done")));
  }, [todos, filter]);

  // ...
}

visibleTodos is a copy that must be kept in sync. Every change renders once with the stale list and then again after the Effect, and any code path that forgets the Effect shows wrong data. Compute it during render instead:

JSX
function TodoList({ todos }) {
  const [filter, setFilter] = useState("all");
  const visibleTodos = todos.filter((todo) => filter === "all" || todo.done === (filter === "done"));

  // ...
}

react.dev's rule: when something can be calculated from the existing props or state, don't put it in state; calculate it during rendering. If the calculation is genuinely expensive, wrap it in useMemo; it is still derived, just cached.

Store ids, not copies

Keeping selectedItem next to items duplicates one object in two places: edit the item, and the selection shows the old title. Store selectedId and find the item during render: items.find((item) => item.id === selectedId).

Make contradictions impossible

isSending and isSent as two booleans allow a state that should never exist: both true. One status variable with the values "typing", "sending" and "sent" cannot contradict itself.

Don't mirror props

JSX
function Message({ messageColor }) {
  const [color, setColor] = useState(messageColor);
  // ...
}

useState uses its argument only on the first render, so when the parent later passes "red", color stays "blue". Use the prop directly. If you really want only the first value, say so in the name: initialColor or defaultColor.

MiddleFramework

Lifting state up, context and its re-render cost

When two components must change together, react.dev's answer is to lift state up: remove it from both, keep it in their closest common parent and pass it down with an event handler that changes it. For each unique piece of state one component "owns" it; this is the single source of truth.

Lifting can make props travel through components that don't use them. Before reaching for context, react.dev suggests two things: just pass props (explicit data flow is easy to follow), or extract components and pass JSX as children, so that <Layout><Posts posts={posts} /></Layout> replaces <Layout posts={posts} />.

What context costs

Context delivers a value to any depth. The price is how updates work: React re-renders every component that reads the context, starting from the provider whose value changed, comparing old and new values with Object.is. Wrapping consumers in memo does not prevent this.

JSX
function ShopProvider({ children }) {
  const [cart, setCart] = useState([]);
  const [theme, setTheme] = useState("light");
  const addToCart = (product) => setCart((lines) => addLine(lines, product));

  return (
    <ShopContext value={{ cart, addToCart, theme, setTheme }}>
      {children}
    </ShopContext>
  );
}

Two problems are hidden here:

  1. The value object is created on every render, so every consumer re-renders whenever ShopProvider renders for any reason.
  2. Unrelated data shares one value. A product card that only needs addToCart still re-renders when the cart changes, because the object holding addToCart is new.

Fixes, in order of impact

  • Move state down. State that one component uses (a draft in a single text field) does not belong in a shared context at all.
  • Split contexts by what changes together, and give actions a context of their own. setState functions never change, so an actions value built once stays stable.
  • Stabilize values with useMemo for objects and useCallback for functions. This stops re-renders caused by the provider re-rendering, but not those caused by a real change: memoizing a value that bundles everything still changes it whenever any part of it changes.
  • Use an external store with selectors when many components each need a small slice of frequently changing state.

Context is a good fit for values that are read in many places and change rarely: the theme, the current account, the locale, the router.

The Context storm challenge in Weekly Challenges lets you practise finding and removing context re-renders: one shop context holds the user, the theme, the cart and a gift note, and adding a single plant re-renders all 24 product cards.

MiddleExample

Reducers and immutable updates

When several event handlers update the same state in related ways, useReducer moves that logic into one pure function: (state, action) => nextState. Components only describe what happened (dispatch({ type: "added", product })), and the reducer decides how the state changes.

JavaScript
function cartReducer(state, action) {
  switch (action.type) {
    case "added": {
      const exists = state.lines.some((line) => line.id === action.product.id);
      const lines = exists
        ? state.lines.map((line) =>
            line.id === action.product.id ? { ...line, qty: line.qty + 1 } : line,
          )
        : [...state.lines, { id: action.product.id, qty: 1 }];
      return { ...state, lines };
    }
    case "cleared":
      return { ...state, lines: [] };
    default:
      return state;
  }
}

Why immutability is not a style preference

React decides whether something changed by reference. When setState or dispatch receives a value that is Object.is-equal to the current state, React skips re-rendering that component. memo, dependency arrays and store selectors all compare references too. A mutating reducer breaks every one of them:

JavaScript
case "added":
  state.lines.push({ id: action.product.id, qty: 1 });
  return state;

The reducer returns the same object, so React sees no change and the screen does not update, although the data did change. The next unrelated render suddenly shows it, which makes the bug look random. In Strict Mode, React calls reducers twice in development to surface impure code; here that pushes the line twice.

Immutable updates copy only the path that changed and reuse everything else. In the reducer above, unchanged lines keep their references, so a memo(CartLine) component skips them, and a selector that reads state.user does not see a change when the cart changes. This structural sharing is what makes fine-grained re-renders possible. Libraries such as Immer (used by Redux Toolkit's createSlice) let you write mutating-looking code that produces the same immutable result.

Reducer plus context

For a screen whose state many distant components read and change, react.dev combines the two: one context for the state and one for dispatch. dispatch is stable for the component's lifetime, so components that only send actions (an "Add" button) never re-render because the list changed. You can have many such pairs in one app, one per feature.

MiddleWeb platform

External stores: subscribe, snapshots and selectors

Some state lives outside React: a Redux or Zustand store, a module-level cache, a browser API such as navigator.onLine. React cannot see it change, so it needs two things from the store: a way to read the current value (a snapshot) and a way to be told that it changed (subscribe). React's hook for this is useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot?).

A store that fits this contract is small. This is the shape of Zustand's core (createStore in vanilla.ts):

JavaScript
function createStore(createState) {
  let state;
  const listeners = new Set();

  const getState = () => state;
  const setState = (partial) => {
    const next = typeof partial === "function" ? partial(state) : partial;
    if (Object.is(next, state)) return;
    const previous = state;
    state = Object.assign({}, state, next);
    listeners.forEach((listener) => listener(state, previous));
  };
  const subscribe = (listener) => {
    listeners.add(listener);
    return () => listeners.delete(listener);
  };

  state = createState(setState, getState);
  return { getState, setState, subscribe };
}

The state is private to a , listeners sit in a Set, and setState merges shallowly into a new object, so anything that compares references sees the change. The real one also takes a replace flag.

Selectors and equality

JSX
function useStore(store, selector) {
  return useSyncExternalStore(store.subscribe, () => selector(store.getState()));
}

const count = useStore(cartStore, (state) => state.lines.length);

After every store change React calls the snapshot function again and re-renders the component only if the result differs by Object.is. A selector is how a component says "I only care about this slice". Equality is the rule that decides what counts as a change:

  • Selecting a primitive (lines.length) or an existing reference (state.user) works with Object.is.
  • Selecting a newly built object or array ({ count, total }, lines.map(...)) gives a new reference on every call. React-Redux's useSelector (=== by default) then re-renders on every action; with useSyncExternalStore it can loop forever. Use a shallow comparison (shallowEqual in React-Redux, useShallow in Zustand) or select values one by one.

Redux calls every listener after every dispatch, even if the reducer returned the same state; it is the selector comparison in useSelector that keeps components from re-rendering.

On the platform

In the Mini State Library project (Build Your Own X) you write this from scratch: a Redux-style store, subscriptions, selectors with an equality function, middleware and a hook on useSyncExternalStore. The tour Zustand: the whole store in 164 lines reads the real vanilla.ts and react.ts at v5.1.0.

SeniorFramework

Tearing, concurrent rendering and stable snapshots

Since React 18, rendering can be concurrent: during a transition React may pause a render to handle input and continue later. React keeps its own state (useState, context) consistent across such pauses, but it cannot protect values it does not own. If a component reads a mutable store directly during render and the store changes while React is paused, components rendered before the change show the old value and those rendered after it show the new one. The React 18 working group calls this tearing: the UI shows multiple values for the same state.

useSyncExternalStore exists to prevent it. React reads the store only through getSnapshot and checks it before committing: react.dev says that for a transition update React calls getSnapshot a second time just before applying changes to the DOM, and if the value changed, it restarts the update as a blocking one, so every component on screen reflects the same version of the store. The trade-off is that updates caused by a store change are synchronous; they cannot be time-sliced the way useState updates in a transition can.

The snapshot contract

While the store has not changed, repeated calls to getSnapshot must return the same value (by Object.is). React calls it during every render and after every store notification; a different value means "re-render".

JSX
const summary = useSyncExternalStore(store.subscribe, () => ({
  count: store.getState().todos.length,
}));

This snapshot is a new object on every call, so React never sees a stable value. React 19 logs "The result of getSnapshot should be cached to avoid an infinite loop" and then stops with "Maximum update depth exceeded". The fixes:

JSX
const count = useSyncExternalStore(store.subscribe, () => store.getState().todos.length);

const { count, add } = useTodoStore(
  useShallow((state) => ({ count: state.todos.length, add: state.add })),
);

The first returns a primitive. The second is Zustand: its docs warn that a selector returning a new reference on every render can trigger infinite update loops in v5, and useShallow returns the previous object while its fields are shallowly equal. React-Redux takes a third route: it uses useSyncExternalStoreWithSelector, which memoizes the selection.

Two more rules

  • subscribe must be stable. A new function on each render makes React unsubscribe and subscribe again every time; declare it outside the component or memoize it.
  • Snapshots are immutable. If the source is mutable, return a cached snapshot and replace it only when the data changes.

For server rendering, the third argument getServerSnapshot must return the same value on the server and during hydration; without it, rendering the component on the server throws. Zustand passes the store's initial state there, which is why a server render shows the initial state.

SeniorFramework

Server state is a cache, not state

The TanStack Query docs describe what makes server state different: it is persisted remotely in a place you don't control, needs asynchronous APIs, is shared with other people who can change it, and can go out of date. Putting it in a client store as { data, loading, error } means writing a cache by hand: when to refetch, how to avoid duplicate requests, how to drop old data, how to handle out-of-order responses. Most apps get some of that wrong.

A server-state library owns the cache:

JSX
function useProducts(sort) {
  return useQuery({
    queryKey: ["products", { sort }],
    queryFn: () => fetchProducts({ sort }),
    staleTime: 60_000,
  });
}

function useAddReview() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: postReview,
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ["products"] }),
  });
}

How TanStack Query behaves (v5)

  • One cache entry per key. The queryKey is hashed into a stable string. Two components with the same key share one query, so mounting both at once sends one request (deduplication). Every value the query function uses belongs in the key; a missing one makes different requests share one entry, such as the results for one filter shown for another.
  • staleTime defaults to 0: cached data is considered stale at once. Stale data is still shown immediately; it is refetched in the background when a new component using the query mounts, when the window is refocused and when the network reconnects. Staleness is checked at those moments; nothing is fetched just because the time ran out.
  • gcTime defaults to 5 minutes: a query with no mounted users (inactive) is removed after that.
  • Failures are retried 3 times with exponential backoff before the query shows an error.
  • Structural sharing: a refetch that returns equal JSON keeps the old references, so components and memoized selectors see no change.
  • invalidateQueries marks matching queries stale (a key prefix matches every key that starts with it) and refetches the ones that are being rendered.

isPending means there is no data yet; isFetching is true during any fetch, including a background refetch. Showing a spinner for isFetching makes every window focus flash a loader.

The TanStack Query tour TanStack Query: the life of useQuery follows one call through QueryClient, QueryCache, Query and QueryObserver: one shared query per key, one observer per component.

What is left for the client store

TanStack's docs are explicit that the library is not a replacement for client state management. Once server data moves into a query cache, the remaining global client state is usually small: the theme, a draft, UI flags, sometimes a cart. That is the real payoff: the client store shrinks to what the client actually owns.

SeniorPitfalls

Choosing the right home, and common mistakes

Choosing between Redux Toolkit, Zustand or plain context matters less than choosing the right home for each piece of state. Most "state management problems" are state in the wrong place. Ask, in order:

  1. Can it be computed from props, other state or the URL? Then don't store it.
  2. Does it come from the server? A server-state cache or the framework's data loading, never a copy in a client store.
  3. Should it survive a reload or be shareable? The URL.
  4. Is it a form being filled in? The form, or a form library.
  5. Does one component use it? useState there.
  6. Do a few nearby components use it? Lift it to their common parent.
  7. Do many distant components read it, and does it change rarely? Context.
  8. Do many components each need a slice of it, and does it change often? An external store with selectors.

Mistakes seen in real code

  • API data copied into Redux or Zustand. It goes stale, the same list is fetched by three components, and every mutation needs manual updates in several places.
  • Filters and pagination in useState. Refresh loses them, the Back button ignores them, and nobody can share the link.
  • Every keystroke in a global store. Each change runs every subscriber's selector and makes local behaviour global. Keep input state local and commit it on submit or with a debounce.
  • One giant context. Every consumer re-renders on every change.
  • Selectors that build new objects without a shallow comparison: re-renders on every change, or an infinite loop.
  • Effects that sync one state into another. If the second value can be computed, compute it; if it is a reaction to an event, do it in the event handler.
  • Mutating state and wondering why the UI does not update.

A practical default

For a typical React app: useState and useReducer locally, the URL for anything shareable, a server-state library (or Server Components and loaders) for API data, and one small client store or a couple of focused contexts for what remains. Add a library when a real need appears: many components reading slices of frequently changing state, middleware such as logging or persistence, or devtools.

SeniorInterview tips

Interview tips

A 30-second answer. "First I decide what kind of state it is: local UI, shared client, server, URL or form state. Each has a natural home: useState, a common parent or context, a server-state cache, the URL, the form. I don't store what I can derive. For shared state read by many components I use an external store with selectors on useSyncExternalStore, so components re-render only when their slice changes."

Questions you are likely to get

  • Context or Redux/Zustand? Context passes a value down; every consumer re-renders when it changes. A store with selectors lets each component subscribe to a slice. Context suits rarely changing values (theme, account, locale).
  • Why do my components re-render? Walk through the causes: the parent rendered, a new context value (often an inline object), a selector that returns a new object, state stored twice and synced in an Effect.
  • Why immutable updates? React, memo, dependency arrays and selectors compare references with Object.is. Mutation gives the same reference, so nothing updates; copying the changed path keeps unchanged parts identical.
  • What is tearing, and why does useSyncExternalStore exist? Concurrent rendering can pause; a store that changes meanwhile shows two values on one screen. useSyncExternalStore checks the snapshot before committing and falls back to a blocking render.
  • Why not keep API data in Redux? Server state needs caching, deduplication, background refetching and invalidation. Name staleTime (0 by default), gcTime (5 minutes) and invalidateQueries.
  • Implement a tiny store. A closure with state, a Set of listeners, getState, setState with an Object.is check, subscribe returning an unsubscribe function, and a hook on useSyncExternalStore.

Mistakes that cost points

  • Saying memo stops context re-renders. It does not.
  • Returning a new object from getSnapshot or a selector without shallow equality.
  • Treating "global state" as one bucket instead of separating server, URL and client state.
  • Picking a library before describing the state.

Senior signal

Talk in trade-offs: synchronous store updates versus transitions, the cost of a provider value versus selector subscriptions, cache keys that include every input, and how you would measure a re-render problem with the React DevTools Profiler before changing the architecture.

JuniorReview checklist

What to check when reviewing state and stores

Use this list when you review state code you did not write: a teammate's, a library's or an AI assistant's. Most state bugs are state in the wrong place or shape: two copies that disagree, a filter lost on reload, a screen that does not update.

  • Is any state a copy of something that can be computed? A useState synced by an Effect renders stale data first and drifts once a code path forgets it; compute the value during render. Store selectedId, not a copy of the item, and don't copy a prop into useState: its argument is read only on the first render.
  • Is state changed without mutation? React, memo and selectors compare references with Object.is, so mutating state with push, sort() or state.field = … leaves the screen unchanged. Each changed level needs a new object or array, such as { ...state, lines }.
  • Does API data live in a server-state cache rather than a copy in a client store? A copy goes stale, gets fetched by several components and needs manual updates after every mutation. In a query cache, every value the query function uses belongs in the key, or different requests share one entry.
  • Do filters, sort order and page number live in the URL? In useState they vanish on reload, the Back button ignores them and the link cannot be shared. Set a filter, reload and press Back.
  • Do selectors and getSnapshot return a primitive or an existing reference? A newly built object or array ({ count, total }, .map(…)) is new on every call: the component re-renders on every store change, and with useSyncExternalStore it can loop forever. Select values one by one or compare shallowly.

Check your understanding

  • Practice

    Predict-output and open interview questions with self-assessment.

    3 predict-output · 4 open

  • Quiz

    Multiple-choice questions with explanations and a score.

    6 questions

Hands-on work that uses this topic.

Guided tours through the source of real libraries that rely on it.