Skip to content

How useState works under the hood

How React tracks state under the hood, from Fiber nodes and update queues to Object.is comparisons and automatic batching.

useState looks simple. Call const [count, setCount] = useState(0) and React tracks the value for you. Behind that one line sits a system of memory management, update queues, and reconciliation logic that decides how and when your component re-renders. It shares the same foundation as useEffect.

Most of us treat useState as a black box. It works, until an app grows and a re-render happens for no obvious reason, or performance turns critical. That's when knowing what's underneath actually saves debugging time. So where does React keep your state between renders, and what decides when a setter causes a re-render? If you use useState every day but have never looked inside it, you have all the background you need.

State lives on the component's fiber

Your state isn't stored in your component function. It lives on a fiber, an object React keeps for each component.

Fiber nodes

React's internal architecture is built around a data structure called Fiber. Each component you write becomes a fiber node, and together they form a tree that mirrors your component tree.

Every fiber node carries what React needs to know about that component:

  • stateNode: the actual component instance or DOM node
  • child: the first child fiber
  • sibling: the next fiber at the same level
  • return: the parent fiber
  • memoizedState: where your hooks live
  • alternate: the fiber's other version, used during updates

When you call useState, React doesn't drop your state into an arbitrary memory slot. It builds a linked list attached to the component's fiber node, and each useState call becomes one link in that list, stored in memoizedState.

The work-in-progress tree

React uses double bufferingPreparing the next version off-screen, then swapping it in so users never see a half-finished one. Read more ↗. Rather than editing your component tree directly, it builds a separate "work-in-progress" tree and applies every update there first.

That separation gives React a few guarantees:

  • React finishes all updates before anything renders on screen
  • Updates can pause and resume without exposing a half-finished state
  • Comparing the work-in-progress tree against the current one shows exactly what changed
  • If something goes wrong mid-update, the current tree stays untouched

Only after the work-in-progress tree is fully ready does React commit it, swapping it in as the new current tree. That's what keeps you from ever seeing an in-between state.

React finds your state by call order

React doesn't know your state by its variable name. It knows it by which useState call it was, first, second, third.

Mount vs. update

useState behaves differently on a component's first render than on every render after that.

On the first render, the "mount", React calls mountState(), which:

  1. Creates a new hook object with mountWorkInProgressHook()
  2. Stores the initial state in both hook.memoizedState and hook.baseState
  3. Creates an update queue for future state changes
  4. Binds dispatchSetState as the setter function you call, like setCount

The hook object looks like this:

const hook = {
  memoizedState: initialState, // Current state value
  baseState: initialState, // Base state for updates
  baseQueue: null, // Base update queue
  queue: {
    // Update queue configuration
    pending: null,
    lanes: NoLanes,
    dispatch: null,
    lastRenderedReducer: basicStateReducer,
    lastRenderedState: initialState,
  },
  next: null, // Reference to next hook
};

On every render after the mount, React calls updateState() instead. It walks to the existing hook in the linked list and processes whatever updates are pending, rather than creating anything new.

Hook call order matters

React matches hooks to their stored data by position, not by name. As it processes your component function, it walks a pointer through the hook linked list, one step per hook call. That's why the Rules of Hooks exist:

  • No hooks inside conditions, loops, or nested functions
  • Call hooks in the same order every render
  • Only call hooks from React function components or custom hooks

Break these rules and React can't line up your hook calls with their stored values. The result is state corruption and behavior that doesn't map to anything in your code.

The most common way to break them is an early return between two hooks.

function Profile({ user }) {
  const [tab, setTab] = useState("posts");
  if (!user) return null; // ❌ the hook below only runs on some renders
  const [open, setOpen] = useState(false);
  return <Menu tab={tab} open={open} onToggle={() => setOpen(!open)} />;
}

When user goes from present to missing, this render calls one hook where the last one called two, and React throws "Rendered fewer hooks than expected. This may be caused by an accidental early return statement." Going the other way throws "Rendered more hooks than during the previous render." The fix is to call every hook before any early return.

function Profile({ user }) {
  const [tab, setTab] = useState("posts"); // ✅ both hooks run on every render
  const [open, setOpen] = useState(false);
  if (!user) return null;
  return <Menu tab={tab} open={open} onToggle={() => setOpen(!open)} />;
}

The same goes for a hook inside an if or a loop. You rarely have to wait for the runtime error, though. The eslint-plugin-react-hooks lint rule flags a conditional hook as you type, and asks whether you called it after an early return.

Calling a setter queues an update

When you call a setter like setCount(5), React doesn't update state immediately.

The circular linked list

Instead, it creates an update object and adds it to a circular linked list.

This queue is what lets React batch multiple updates and handle different priority levels. Each update object carries what React needs to process it later:

const update = {
  lane: updateLane, // How urgent is this update?
  action: newValue, // What's the new value or function to run?
  hasEagerState: false, // Did we already figure out the result?
  eagerState: null, // The eagerly computed result (if any)
  next: null, // Who's next in line?
};

Updates first land in a global concurrentQueues array, and React moves them onto the hook's queue once no render is in progress, usually at the start of the next one. That two-stage handoff lets React accept updates that arrive mid-render without corrupting the render already in progress.

Priority-based updates

React's concurrent features assign each update a priority through "lanesReact's internal priority levels, stored as bit flags on each update and fiber.":

  • User input, like a click, gets SyncLane and runs first
  • Updates inside startTransition get a transition lane and can be interrupted
  • Background work gets IdleLane and runs last

If a high-priority update arrives while React is working through something lower priority, it pauses the lower-priority work and handles the urgent update first. The paused work isn't lost, it sits in baseQueue until a future render picks it back up.

This priority system is what makes time-slicingSplitting rendering into small chunks so the browser can handle urgent work between them. possible. Instead of processing everything in one block, which would freeze the UI, React breaks the work into pieces it can interrupt when something more urgent comes in. It's working around the same single thread that the event loop manages for everything else in the browser.

Setting the same value usually skips the render

If the new state equals the old one, React can skip the re-render.

The Object.is comparison

React compares state values with Object.is() instead of ===. Object.is() handles NaN correctly and distinguishes +0 from -0, edge cases === gets wrong.

If the new state is identical to the current state by that comparison, React can skip re-rendering the component and its children entirely, a real performance win when nothing actually changed. It's also why mutating an object in state does nothing. user.name = 'Jane'; setUser(user) passes the same reference, Object.is() sees no change, and the screen stays stale. Create a new object instead, like setUser({ ...user, name: 'Jane' }).

React has two kinds of bailout, and they happen at different points ("early" and "regular" are just descriptive names for this post, not terms you'll find in React's own source):

  • Early bailout, before React even schedules a re-render. The cheapest option.
  • Regular bailout, during the render phase itself. Still useful, just later.

Why you sometimes get two renders

One of React's more confusing behaviors: setting state to the value it already has can still trigger a render.

This comes from how conservative the early bailout check is. It requires both the current fiber and its alternate to have no pending work at all (NoLanes). When an update gets enqueued, both fibers get marked dirty, and the alternate fiber's lanes only clear during the actual render. That means the early bailout check can fail on the very next identical update, even though nothing will end up changing.

So the component can render twice before React confirms nothing changed. That's not a bug, it's React trading an occasional extra render for correctness.

Automatic batching turns many updates into one render

Before React 18, batching only happened inside React event handlers like onClick or onChange. Updates inside promises, timeouts, or native event handlers each triggered their own render.

React 18 batches updates automatically, regardless of where they come from:

// Before React 18: 3 separate renders
setTimeout(() => {
  setCount((c) => c + 1); // Render 1
  setName("John"); // Render 2
  setEmail("john@example.com"); // Render 3
}, 1000);

// React 18: 1 batched render
setTimeout(() => {
  setCount((c) => c + 1); // Queued
  setName("John"); // Queued
  setEmail("john@example.com"); // All batched into one render
}, 1000);

For apps that update state frequently, this cuts out renders that were never doing useful work.

Stale closures keep reading old state

A closure that captures old state and never sees the updated value is one of the most common gotchas in React. Before reading on, guess what this counter shows after five seconds.

function Timer() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    const timer = setInterval(() => {
      setCount(count + 1); // ❌ Stale closure - always adds 1 to initial value
    }, 1000);

    return () => clearInterval(timer);
  }, []); // Empty dependency array causes stale closure

  return <div>{count}</div>;
}

It shows 1, and stays there. The interval callback was created on the first render, when count was 0, and the empty dependency array means it's never replaced. Every tick sets 0 + 1.

The fix is a functional update, or including the right dependencies:

function Timer() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    const timer = setInterval(() => {
      setCount((prevCount) => prevCount + 1); // ✅ Always uses current value
    }, 1000);

    return () => clearInterval(timer);
  }, []); // Now safe with functional update

  return <div>{count}</div>;
}

useEffect's dependency tracking makes sure the effect only re-runs when it needs to, while the functional update avoids reading a stale value.

FAQ

How does useState maintain state between renders?

useState stores values in fiber nodes, inside a linked list held on the fiber's memoizedState property. On re-render, React doesn't recreate that state, it reads it back from the fiber.

Why do hook calls need to be in the same order every time?

React matches hook calls to their stored data by position, not by name. A different call order means React can't line up the right call with the right data, which produces state corruption. That's why conditional hook calls aren't allowed.

What happens when I set state to the same value?

React runs an Object.is() check against the current state. If they match, React tries to bail out of re-rendering. Because of how the bailout condition is structured, you can still see one or two renders before React confirms nothing changed. That's an intentional trade-off, not a bug.

How does automatic batching work in React 18?

React 18 groups multiple state updates into a single render regardless of where they originate, promises, timeouts, and event handlers included. Earlier versions only batched updates inside React event handlers, so each of those other cases got its own render.

Can useState cause memory leaks?

Not by itself. React drops a component's state when it unmounts. Leaks come from things that outlive the component, like a timer, subscription or pending request with no effect cleanup that still holds on to the setter.

How do I debug complex useState behavior?

Start with React DevTools for inspecting state values. Add useDebugValue to custom hooks for better visibility, and log state changes directly when needed. Most of this comes down to understanding the component's lifecycle and what triggers each re-render.

What's the difference between setState in class components and useState?

Class setState merges the object you pass into existing state automatically. useState replaces the value outright, so you spread the old state yourself if you want to merge. useState also supports functional updates, and each call manages one independent piece of state rather than one shared object.

How does useState work with concurrent features?

Updates can be interrupted, resumed, prioritized, and batched automatically without any extra code from you. With Suspense, if an already-visible component suspends during an update, React hides it behind the fallback without unmounting it, so its state survives. A component that suspends before it ever mounted has no state to keep yet, so it starts fresh once its data arrives.

Wrapping up

Understanding useState's internals changes how you read a bug report. Fiber nodes, call order, update queues and bailouts aren't separate trivia, they're the reasons your component re-renders when it does.

That understanding pays off in specific ways: you can tell why a re-render happened instead of guessing, spot hook order violations and stale closures on sight, and design state that works with React's optimizations instead of against them.

useState looks simple on the surface. The mechanics underneath, fiber nodes, lanes, bailouts, batching, are what make it fast at scale. None of this is academic. It's the same foundation useEffect is built on, so the next time a side effect fires at the wrong moment, this is where to start looking.