Kinds of state

Local, shared, server, URL, form, persisted and derived.

Builds on Context.

Part 3 gave you the tools: useState, useReducer, context, custom hooks. Part 6 is about the question those tools don't answer: where should each piece of state live? Most "state management" pain in real apps isn't caused by picking the wrong library. It's caused by putting the right data in the wrong place: server data copied into a client store, a value that could be computed stored as state, a filter that should be in the URL kept in a component that unmounts.

So before any store, any Redux or Zustand, this chapter sorts state into kinds. Each kind has a natural home, and each wrong home has a specific, predictable bug. Once you can name the kind, the tool usually picks itself, and you'll find that the part of your app that needs a "state management library" is much smaller than it looked.

The problem: one bag called "state"#

Here's a version of the reading list that treats everything as state. It holds the books, and it also keeps an unread counter in state, updated by hand. Toggle a book to read, then toggle it back.

A counter that drifts
import { useState } from "react";
import { books as fixture } from "guide-tools";

const initial = fixture.slice(0, 4).map((b) => ({ ...b, read: b.id === 1 }));

export default function App() {
  const [list, setList] = useState(initial);
  // A second copy of something the list already knows.
  const [unread, setUnread] = useState(3);

  function toggle(id: number) {
    setList((l) => l.map((b) => (b.id === id ? { ...b, read: !b.read } : b)));
    setUnread((n) => n - 1); // assumes every toggle marks a book as read
  }

  return (
    <div>
      <p>Unread: {unread}</p>
      <ul>
        {list.map((b) => (
          <li key={b.id}>
            <label>
              <input type="checkbox" checked={b.read} onChange={() => toggle(b.id)} /> {b.title}
            </label>
          </li>
        ))}
      </ul>
    </div>
  );
}

Check "Refactoring" and the counter says 2. Uncheck it and the counter says 1. The list is right and the counter is wrong, which is the exact bug from the first chapter, just moved inside React: two copies of one truth, kept in sync by hand. React solved the DOM copy for you. It can't solve the copies you create yourself.

The fix isn't a better setUnread. It's noticing that unread was never state in the first place. That's the first kind on the list.

Seven kinds of state#

Here's the taxonomy this part of the guide uses. Each kind is defined by who owns the truth and how long it needs to live, not by what it looks like in code.

  • Derived: anything you can compute from other state or props. Owner: nobody, it's a function. Lifetime: one render.
  • Local UI: a dropdown is open, a tab is selected, a tooltip is hovered. Owner: one component. Lifetime: while it's mounted.
  • Shared client: data that lives only in the browser and that several distant components read or change, like a multi-select or a wizard's progress. Owner: the client app.
  • Server cache: a copy of data the server owns, like GET /books. Owner: the server. The client only holds a snapshot that goes stale.
  • URL: the route, search params, the hash. Owner: the address bar. Lifetime: survives reloads, back and forward, and can be shared as a link.
  • Form: what the user is typing before they submit. Owner: the form, until submit hands it to someone else.
  • Persisted: preferences and drafts that must survive closing the tab. Owner: browser storage (or the server, if it must follow the user across devices).

These aren't exclusive in every case. A theme preference is persisted and shared. A search filter is URL state and the input to a server query. But for each piece of data you can almost always say which kind is primary, and that tells you where the source of truth goes. Everything else reads from it.

Where should this state live?
Ask in order, stop at the first yesComputable from other state or props?yesDerive it during rendernoDoes the server own it?yesServer cache (TanStack Query, SWR)noShould a link or reload restore it?yesURL: path and search paramsnoIs it an unsaved form draft?yesForm state (inputs, form library)noMust it survive closing the tab?yesPersisted: storage plus a storenoUsed by one component or subtree?yesLocal: useState or useReducernoShared client: context or a store
Step 1 of 8

Ask the questions in order and stop at the first yes. The order matters: the cheapest home for state (no state at all) comes first, and a global store comes last.

The order of the questions is deliberate. The first question asks whether you need state at all. The last one, the only one that ends in a store, is what's left after everything else found its home.

Derived state: compute it, don't store it#

Back to the drifting counter. The fix is one line: delete the unread state and compute it.

const unread = list.filter((b) => !b.read).length;

Now there's one source of truth (the list) and the count is a pure function of it, recomputed on every render. It can't drift because there's nothing to keep in sync. react.dev states the rule directly in its guide to structuring state: if you can calculate something from props or existing state, don't put it in state.

People resist this for two reasons, and both are usually wrong.

"Computing it every render is wasteful." Filtering a few hundred items is microseconds. If you've measured and it really is expensive, useMemo (or the React Compiler, which does this for you) caches the result. Memoizing a derivation still leaves one source of truth. Storing it doesn't.

"I'll keep it in sync with an effect." This is the most common version of the bug:

const [unread, setUnread] = useState(0);
useEffect(() => {
  setUnread(list.filter((b) => !b.read).length);
}, [list]);

It's correct eventually, but it's slower and briefly wrong. Every change to list renders once with the old unread, commits that inconsistent UI, runs the effect, then renders again. You've paid for two renders to get one value, and any code that reads unread in between sees a stale number. The effects chapter called this "you might not need an effect"; this is the canonical case.

A related trap is mirroring props in state: const [name, setName] = useState(props.name). The state is initialized from the prop once and then ignores it. If you really want "an initial value the user can then edit", name the prop initialName so the intent is obvious. If you want the prop's current value, just use the prop.

Local UI state: as close as possible#

Whether a menu is open, which accordion panel is expanded, what the hover target is: this state matters to one component, or to a small subtree. It belongs in useState (or useReducer when updates get involved) in the lowest component that needs it.

Keeping it low isn't just tidiness. When state lives high in the tree, every update re-renders everything below it. When a dropdown's isOpen sits in a top-level store, opening it can re-render the whole page. When it sits in the dropdown, opening it re-renders the dropdown. The memoization chapter called this "move state down", and it's the cheapest performance fix there is.

Local state also gets something for free that global state doesn't: cleanup. When the component unmounts, its state is gone. A modal's half-typed form doesn't haunt the next time it opens. Put that same state in a global store and you now own its reset logic.

The rule: start local, and lift state up only when a second component genuinely needs it. Lift it to the closest common parent, not to the top.

Server cache: you don't own it#

This is the most expensive misplacement, and interviewers ask about it constantly.

When you fetch /books and store the result in useState or in a Redux slice, it feels like you have "the books". You don't. The server has the books. You have a snapshot taken at one moment, and from that moment on it can go stale: another tab adds a book, a teammate deletes one, your own mutation changes the count. Server data in the client is a cache, and caching is a hard problem with a list of sub-problems: deduplicating identical requests, deciding when data is stale, refetching on focus or reconnect, invalidating after a mutation, garbage-collecting data nobody's looking at, handling loading and error states, and avoiding race conditions.

Here's the stale-copy bug in miniature. Two components each fetch the books and copy them into their own state. Add a book.

Two copies of server data
import { useEffect, useState } from "react";
import { fakeFetch } from "guide-tools";

type Book = { id: number; title: string };

function BookCount() {
  const [count, setCount] = useState<number | null>(null);
  useEffect(() => {
    fakeFetch("/books").then((b: Book[]) => setCount(b.length));
  }, []);
  return <p>Header says: {count ?? "loading"} books</p>;
}

function BookList() {
  const [list, setList] = useState<Book[]>([]);
  async function load() {
    setList(await fakeFetch("/books"));
  }
  useEffect(() => {
    load();
  }, []);
  async function add() {
    await fakeFetch("/books", { method: "POST", body: { title: "New book " + list.length, author: "You", year: 2026, tags: [] } });
    load(); // this component remembers to refetch...
  }
  return (
    <div>
      <button onClick={add}>Add a book</button>
      <p>List shows: {list.length} books</p>
    </div>
  );
}

export default function App() {
  return (
    <>
      <BookCount />
      <BookList />
    </>
  );
}

After one click the header says 10 and the list says 11. Nothing is broken in either component; each one is a correct, isolated cache with no invalidation. Moving both copies into one Redux slice fixes this particular pair, but now you're writing isLoading, error, lastFetched, refetch-after-mutation and dedupe logic by hand in every slice, which is exactly what server-cache libraries already do.

So the home for server data is a server-cache tool: TanStack Query, SWR, RTK Query, or, in a framework with Server Components, fetching on the server so the client never holds a copy at all. These tools key data by what it is (["books"], ["book", 3]), share one cache entry across every component that asks, and give you invalidation as a first-class operation. Chapter 39 covers them in depth.

URL state: the address bar is a store#

Some state should survive a reload and be shareable as a link: which page you're on, the search query, the active filters and sort, the selected tab of a settings page, pagination. If a user can reasonably say "send me the link to what you're looking at", that state belongs in the URL.

Put it in useState instead and three things break: reload resets the filter, the back button doesn't undo a filter change, and a shared link opens the unfiltered page. The URL is a global, persistent, shareable store that the browser already gives you. The only trick is to read from it instead of copying it into state.

The sandbox can't change its real address, so it keeps a virtual one (shown above the preview). Type a filter and watch the URL change. The component has no useState for the query at all.

The filter lives in the URL
import { books, useVirtualLocation, virtualLocation } from "guide-tools";

export default function App() {
  const href = useVirtualLocation(); // re-renders when the URL changes
  const q = new URL(href).searchParams.get("q") ?? "";

  const visible = books.filter((b) => b.title.toLowerCase().includes(q.toLowerCase()));

  return (
    <div>
      <input
        placeholder="Filter titles"
        value={q}
        onChange={(e) => virtualLocation.replace("?q=" + encodeURIComponent(e.target.value))}
      />
      <ul>
        {visible.map((b) => (
          <li key={b.id}>{b.title}</li>
        ))}
      </ul>
    </div>
  );
}

Notice useVirtualLocation is built on useSyncExternalStore, the hook you met in custom hooks. The URL is an external store: something outside React that holds state and tells you when it changes. The next chapter builds your own. Routers (React Router, Next.js) wrap this pattern in hooks like useSearchParams; chapter 40 covers them, and when to use replace versus push for history.

Form state: let the form own the draft#

While a user is filling in "Add a book", the half-typed title is nobody's business but the form's. It isn't app data yet. It becomes app data on submit.

The common misplacement is to wire every keystroke into a global store: dispatch(setDraftTitle(e.target.value)). Now each keystroke runs through the whole store machinery and wakes up every subscriber, a draft that should die with the form lives on after it closes, and validation logic spreads across the store. Keep the draft in the inputs (uncontrolled, read with FormData on submit, which pairs naturally with Actions), in local state, or in a form library such as React Hook Form that's built for this. Hand the finished value to the server or the store once.

Persisted state: storage is a backend, not a store#

A theme choice, a dismissed banner, a draft you want to restore after a crash: these must outlive the tab. The truth then lives in localStorage, sessionStorage or IndexedDB (or on the server if it must follow the user to another device).

But storage isn't reactive. Writing to localStorage doesn't re-render anything, and reading from it on every render is slow and synchronous. So persisted state almost always has two parts: the durable copy in storage, and a live copy in React state or a store that the UI subscribes to, with code that writes through on change and reads back at startup. Each store library in this part has a standard answer for it: Zustand's persist middleware, Jotai's atomWithStorage utility, and for Redux the third-party redux-persist package.

Two costs to know about. First, server rendering: the server has no localStorage, so the first HTML can't include the persisted value, and you have to handle the moment after hydration when the real value arrives. Second, schema changes: what you wrote last month is still on users' machines, so persisted state needs a version and a migration path.

Shared client state: what's actually left#

Take the reading list and remove everything that found a home above. The books themselves are server cache. The filter is in the URL. The "Add book" draft is form state. The unread count is derived. The theme is persisted. Open menus are local.

What's left is the genuinely shared client state: data that exists only in the browser and that distant parts of the tree both read and change. Which books are selected for a bulk action (the toolbar shows "3 selected", each row shows a checkbox). A multi-step checkout's progress. The current editor tool in a drawing app. An optimistic queue of pending changes. It's often a lot smaller than people expect.

For this state you have two built-in options and a family of libraries:

  • Lift state up to the nearest common parent and pass it down. Fine for a few levels.
  • Context, from chapter 16, to skip the prop drilling. Fine when the value changes rarely (theme, current user, locale).
  • An external store (Redux, Zustand, Jotai, or one you build) when the value changes often and many components read different parts of it.

Why does "changes often" push you away from context? Because every consumer of a context re-renders when its value changes, even if the part it reads didn't change. That cost, and a subtler problem called tearing, is what the next chapter is about.

The cost of each wrong home#

Here's the same data in the wrong places, with the bug you get. This table is a good thing to be able to reproduce from memory.

MisplacementWhat breaks
Derived value stored in stateDrift between copies; with an effect, an extra render and a moment of wrong UI
Server data copied into useState or a client storeStale data, duplicate requests, hand-written loading, error and invalidation logic
URL-worthy state in useStateReload loses it, back button doesn't undo it, links can't share it
Form draft in a global storeEvery keystroke wakes subscribers; drafts outlive the form; reset logic everywhere
Persisted state read straight from storageNo re-render on change; SSR mismatch; no migration path
Local UI state in a global storeWide re-renders, manual cleanup, and coupling for no benefit
Fast-changing shared state in one contextEvery consumer re-renders on every change
Shared state copied into many local statesThe drift bug again, across components

Pitfalls#

Check your understanding#

Fix itStop the counter drifting

This is the drifting reading list, plus an Add a book button that never updates the counter. Make the unread count correct for every toggle and every added book. Don't add more setUnread calls; there's a smaller fix.

import { useState } from "react";
import { books as fixture } from "guide-tools";

const initial = fixture.slice(0, 4).map((b) => ({ ...b, read: b.id === 1 }));

export default function App() {
  const [list, setList] = useState(initial);
  const [unread, setUnread] = useState(3);

  function toggle(id: number) {
    setList((l) => l.map((b) => (b.id === id ? { ...b, read: !b.read } : b)));
    setUnread((n) => n - 1);
  }

  function add() {
    setList((l) => [...l, { id: Date.now(), title: "Crafting Interpreters", author: "Robert Nystrom", year: 2021, tags: [], read: false }]);
  }

  return (
    <div>
      <p>Unread: {unread}</p>
      <ul>
        {list.map((b) => (
          <li key={b.id}>
            <label>
              <input type="checkbox" checked={b.read} onChange={() => toggle(b.id)} /> {b.title}
            </label>
          </li>
        ))}
      </ul>
      <button onClick={add}>Add a book</button>
    </div>
  );
}
PredictSyncing with an effect

A component keeps a derived value in state and syncs it with an effect. The user clicks the button once. How many times does Summary render after the click, and what does the first of those renders log?

function Summary({ list }: { list: { read: boolean }[] }) {
  const [unread, setUnread] = useState(list.filter((b) => !b.read).length);
  useEffect(() => {
    setUnread(list.filter((b) => !b.read).length);
  }, [list]);
  console.log("render, unread =", unread, "real =", list.filter((b) => !b.read).length);
  return <p>Unread: {unread}</p>;
}

The click marks one of three unread books as read in the parent.

Quick checkPick the home

A dashboard shows orders from the API, filtered by a date range the user picks. Product wants the filtered view to be bookmarkable. Where should the date range and the orders live?

Quick checkIs it state?

A cart stores items with prices and quantities. Where should the cart total live?

Explain it out loudKinds of state

An interviewer asks: "How do you decide where state lives in a React app?" Answer in about a minute, with an example.

Interview angle

Say it in 30 seconds

I classify state by who owns the truth and how long it lives. Derived values aren't state, I compute them. Server data is a cache, so it goes in a server-cache tool that handles staleness and invalidation. Anything a link or reload should restore goes in the URL. Unsaved input belongs to the form, and preferences that outlive the tab go to storage with a live copy in memory. What's left is local UI state, kept as low as possible, or shared client state, which goes in context if it changes rarely and in a store if it changes often. Most state bugs are the right data in the wrong home.

How do you decide where a piece of state should live?

basic

Why shouldn't you keep server data in a client store like Redux or Zustand?

intermediate

What happens when you store derived data in state and keep it in sync with useEffect?

intermediate

What state belongs in the URL, and what goes wrong if you keep it in component state instead?

basic

Your shared client state changes several times a second and many components read different parts of it. Context or a store, and why?

senior

A team puts everything in one global store: API responses, modal flags, form drafts. What are the costs, and how would you migrate?

senior

Recap#

  • Classify state by who owns the truth and how long it lives: derived, local UI, shared client, server cache, URL, form and persisted.
  • Ask in order: can it be computed, does the server own it, should a link restore it, is it a draft, must it outlive the tab, is it used in one place. A store is what's left.
  • Derived values stored as state drift; syncing them with effects costs an extra render and a stale commit. Compute them, and memoize only if measured.
  • Server data in the client is a cache. It needs staleness, deduplication and invalidation, which server-cache libraries provide and plain stores don't.
  • The URL and storage are external stores: read from them instead of copying them into state, and subscribe so the UI reacts.

Sources#