Skip to content

Where state lives

Placing each piece of UI state at the narrowest scope that fits who reads it, who changes it and how long it must survive: one component, a shared parent, a store, the URL, a server cache or browser storage.

On this page

What it is

On this page, "state" means whatever the interface keeps track of while it is in use: which menu is open, which row is selected, what was typed in the search box, the list the server sent back. "Where state lives" is the decision of which part of the app owns each of those values. React's guidance is a single source of truth per piece of state: one specific component holds it, and others read it from there rather than keeping their own copy. That doesn't put all state in one place; it gives each value exactly one owner, so two copies don't drift apart.

The placement follows from three questions. Who reads the value? Who changes it? How long does it have to live: one render, while the component is on screen, across a reload, across a browser restart, or on the server as the record of truth? Our advice is to match the answers to a place: computed during render, local component state, the closest common parent, a context or a client store, the URL, a server cache, and browser storage. A fourth question settles ties: if someone pastes the link to a colleague, should they see the same view? If yes, the value belongs in the URL.

The first place is "nowhere". A value you can calculate from props or from existing state during rendering shouldn't be stored at all: React's docs call that redundant state and show the classic case, a fullName kept in state next to firstName and lastName, where the fix is to compute it in render so there is nothing to keep in sync. The same page warns against copying a prop into state, because state is initialized on the first render and a later prop value is ignored; the exception is when ignoring later values is the intent, signaled with an initial or default prefix on the prop name.

ts
// An orders page, each value placed by who reads it and how long it lives
function OrdersPage() {
  // URL: a reload or a pasted link rebuilds the same view
  const [params, setParams] = useSearchParams();
  const status = params.get('status') ?? 'all';
  const page = Number(params.get('page') ?? '1');

  // Server cache: the server owns orders; the client keeps a copy and refetches by its own rules
  const orders = useQuery({
    queryKey: ['orders', status, page],
    queryFn: () => fetchOrders(status, page),
  });

  // Lifted: the table and the detail panel both need the selection
  const [selectedId, setSelectedId] = useState<string | null>(null);

  // Derived: computed from the cache, not stored
  const selected = orders.data?.items.find((o) => o.id === selectedId) ?? null;

  return (
    <>
      <StatusFilter value={status} onChange={(s) => setParams({ status: s, page: '1' })} />
      <OrdersTable rows={orders.data?.items ?? []} selectedId={selectedId} onSelect={setSelectedId} />
      <DetailPanel order={selected} />
    </>
  );
}

function ColumnMenu() {
  // Local: one component reads and writes it, nothing else cares
  const [open, setOpen] = useState(false);
  // ...
}

When to use it

Lift state when two components must agree. React's accordion example starts with each panel owning its own isActive flag, then moves the decision to the parent as a single activeIndex once the requirement becomes "one panel open at a time". Two independent booleans can both be true; one index can't point at two panels. The children receive the value and a handler as props, which is also what makes them "controlled": driven by the parent rather than by their own state.

Use context when many components, far apart, need the same value, such as the current theme, the signed-in user or how deep a section is nested. The React docs suggest two things to try first: pass the props, because explicit props show which components use which data, and extract components so a layout takes children instead of forwarding data it doesn't read. A value that still has to cross many layers after that is a fair candidate for context.

Put it in the URL when a reload or a link should rebuild the view, and when the Back button should step through it: the search query, active filters, the page number, the selected tab or item. history.pushState() adds a history entry and replaceState() rewrites the current one; when the person presses Back or Forward the browser fires popstate with the entry's state object. A query parameter is set with url.searchParams.set() and then pushed. Our advice: push an entry for a committed change (a new filter, a new page) and replace for in-progress edits, partly because browsers may throw a SecurityError when pushState() is called too often, and partly so Back doesn't walk through keystrokes.

Treat data the server owns as a cache, not as client state. TanStack Query describes itself as a server-state library that manages the async traffic between server and client, and notes that once that data moves out of a client store, the global client state left behind is usually small. Redux's own FAQ offers rules of thumb for what belongs in a store: do you want to cache it, and do you need it to survive hot-reloading a component? For the shape of such a cache and how it stays fresh, see Client caching and normalized stores.

Use browser storage when a value should outlive the page but has no business in a link: a half-written comment, a dismissed banner, a preferred density. sessionStorage is partitioned by tab and by origin, and closing the tab destroys it; localStorage is partitioned by origin, has no expiration time and persists after the browser is closed and reopened, though a private-browsing copy is cleared when the last private tab closes. localStorage keys and values are strings, so an object has to be serialized before it is written. A storage event fires in other documents of the same origin when a storage area changes, which is the hook behind Coordinating across tabs.

When not to

Don't centralize a flag nobody else reads. The Redux FAQ's example is isDropdownOpen: the rest of the app doesn't care, so in most situations it should stay in component state, and the same reasoning covers most form state, which usually isn't shared. A store or a context for those values adds wiring without adding a reader. Our advice: start with component state and move a value out when a second reader appears.

Don't put it in the URL when a link shouldn't reproduce it. Transient UI such as hover state, an open menu or scroll position within a panel makes a noisy address and a confusing Back button. Our advice: a URL holds what a colleague would want when you paste it to them, and nothing private, since it is made to be copied. A value that still needs to survive navigation can ride in the state object passed to pushState(), though MDN notes some browsers cap the size of that object and points to sessionStorage or localStorage when more room is needed.

Don't make localStorage the record of truth for server data. It has no expiry, so a copy left there is as old as the last write and nothing tells the app that it is stale. A server cache with a stale time gives you the refetch rule; storage is for surviving a restart. When the product has to work without a network, that becomes a deliberate design with its own sync rules, covered in Offline-first storage.

Compared

PlaceScope and lifetimeRight choice whenWhat it costs

Computed in render

Recalculated each render, not stored

The value follows from props or other state, like a full name or a filtered count

Recomputed on each render; memoize when it is expensive

Local component state

One component owns it and reads it in its own render

One component reads and writes it: an open flag, a hover, an input mid-edit

Invisible to siblings; a second reader means moving it to a parent

Closest common parent

The subtree under that parent

Two or more siblings must agree, like one open panel at a time

Props and handlers travel through components in between

Context

The tree under the provider

Many distant components need one value: theme, user, nesting depth

Hides who uses the data; props and children are clearer when they suffice

Client store (Redux and kin)

Whatever code reads the store

Large state with no server copy that is shared widely, such as an editor's document

Wiring and reducers; server data fits a server cache better

The URL

Survives reload; Back and Forward; shareable

A pasted link should rebuild the view: query, filters, page, selection

Strings in the address bar; too many pushState() calls can throw

Server cache

A client copy of server data, usually with a freshness setting

The server owns the record and the client shows a recent view

Can be stale; needs refetch and invalidation rules

sessionStorage

One tab and one origin; destroyed with the tab

Per-tab progress such as a wizard step

Per-tab; destroyed when the tab closes

localStorage

One origin; survives a browser restart; no expiry

Preferences and drafts that should survive a restart

Strings; staleness is yours to manage; cleared when a private session ends

In a picture

Derivable?Compute itOne reader? LocalstateSiblings? CommonparentMany readers?ContextReload or link?The URLServer owns it?CacheOutlives page?Storage
Our advice: read the questions top to bottom and stop at the first that is true for the value. A value the server owns goes to a server cache even when it also survives a reload; a value that is yours and must survive a restart goes to browser storage.

How to say it in an interview

The common mistake

Quiz

A filter sidebar and a results table both read the active filter, and a reload or a shared link should bring the same filtered view back. Where does the filter live?
A form keeps firstName, lastName and fullName in three state variables and updates fullName in both change handlers. What should change?
A comment draft should come back if the person accidentally closes the tab and reopens the page later, but it should not be in any link. Which place fits?
A page shows a list of orders fetched from the API. Which placement treats the data correctly?

Related

Sources

  1. React: Sharing State Between Components
  2. React: Passing Data Deeply with Context
  3. React: Choosing the State Structure
  4. MDN: Web Storage API
  5. MDN: Window: localStorage property
  6. MDN: Working with the History API
  7. MDN: History: pushState() method
  8. TanStack Query: Does TanStack Query replace Redux, MobX or other global state managers?
  9. Redux FAQ: Organizing State
Sign in to report a mistake