Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Rendered more hooks than during the previous render in React

Hook order changed between renders: an early return, a conditional hook or a loop. React has no state slot for the new hook, so the render throws.

~5 min readReact
#React#Hooks#Debugging#Rendering
A React hook slot rail with one extra cube beyond the cyan limit, an amber early return gate below

Introduction & Quick Summary

text
Error: Rendered more hooks than during the previous render.

React counts the hooks a component calls on every render and compares the sequence with the previous one. This error means the current render called more hooks than the last one did, so React has no state slot to give the new hook. It is almost never a React bug: a code path returned early, a condition changed, or a custom hook stopped calling its own hooks on the first pass.

The companion message is Rendered fewer hooks than expected. This may be caused by an accidental early return statement. Both come from the same rule: hook order and count must be identical on every render.

  • Early return above a hook. The first render hits the return, the next one falls through and calls an extra hook.
  • Conditional hook. if (user) useEffect(...) calls a hook on one render and not the next.
  • Thrown render. React discards the failed attempt but keeps the hook count, so the retry can call a different number.
  • Changing loop bounds. items.map(useSomething) calls a variable number of hooks.
MessageMeaningTypical line
Rendered more hooksNew hook with no matching slotHook after a conditional return
Rendered fewer hooksSkipped a hook that ran beforeReturn placed between hooks
Invalid hook callHook called outside a componentHelper function or event handler
Cannot update a component while renderingState write during rendersetState in the body

Core Mechanics, Signatures & Reproducible Setup

React stores hook state in a linked list per fiber. The dispatcher walks that list in call order; the first useState on a render consumes the first slot, the second consumes the second, and so on. If the walk runs past the end of the list, React throws this error instead of allocating, because the new slot has no history and any state it returned would be wrong.

Reproduce it in a single component:

tsx
import { useEffect, useState } from "react"; export function Profile({ userId }: { userId?: string }) { if (!userId) { return <p>No user selected</p>; // first render: 0 hooks } const [name, setName] = useState(""); // second render: 1 hook -> error useEffect(() => { fetch(`/api/users/${userId}`).then((r) => r.json()).then((u) => setName(u.name)); }, [userId]); return <p>{name}</p>; }

The first render with userId unset returns before any hook. When userId arrives, React sees one hook where the previous render had none and throws. The corrected version calls hooks unconditionally and gates only the output:

tsx
export function Profile({ userId }: { userId?: string }) { const [name, setName] = useState(""); useEffect(() => { if (!userId) return; let cancelled = false; fetch(`/api/users/${userId}`) .then((r) => r.json()) .then((u) => { if (!cancelled) setName(u.name); }); return () => { cancelled = true; }; }, [userId]); if (!userId) return <p>No user selected</p>; return <p>{name}</p>; }

The rule is positional, not semantic: two useState calls with the same initial value are different slots, and renaming a variable changes nothing. That is also why hooks cannot be reordered by a later refactor without migrating state.

A second reproduction, using a condition instead of a return:

tsx
export function Panel({ open }: { open: boolean }) { if (open) { const [width, setWidth] = useState(320); // hook inside a branch return <div onClick={() => setWidth(400)}>{width}</div>; } return null; }

Toggling open flips the hook count in both directions, producing "more hooks" on open and "fewer hooks" on close.

Key Comparison Table

PatternHooks per renderReact result
Early return before hooks0 then 1Rendered more hooks
Early return between hooks2 then 1Rendered fewer hooks
Hook inside if1 or 0Both errors, depending on order
Hook inside mapVariableMore or fewer hooks
Hook in a custom hook after a returnVariableSame errors, longer stack
Hook in a try after a throwVariableMore hooks on retry
All hooks at top, output gatedConstantNo error
FixPreserves stateBest for
Move hooks above all returnsYesMost components
Split into two componentsYes, per componentModes with different data
Pass undefined and no-op in effectsYesFetches and subscriptions
Render a keyed childResets child stateSwitching between records
Add react-hooks/rules-of-hooksn/aPreventing regressions

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

Case 1: Feature flag adds a hook

tsx
const [draft, setDraft] = useState(""); if (flags.autosave) { useEffect(() => { // appears only when the flag flips save(draft); }, [draft]); }

Flags are read at runtime and can change after a deploy. Even a flag that is constant per session changes when the provider re-fetches. Convert the conditional hook into an always-called hook whose body checks the flag:

tsx
useEffect(() => { if (!flags.autosave) return; save(draft); }, [draft, flags.autosave]);

Case 2: Custom hooks that return early

tsx
function useOrders(userId?: string) { if (!userId) return { orders: [] }; // skips both hooks below const [orders, setOrders] = useState<Order[]>([]); useEffect(() => { /* fetch */ }, [userId]); return { orders }; }

The fix belongs inside the custom hook, because its callers cannot see the skip:

tsx
function useOrders(userId?: string) { const [orders, setOrders] = useState<Order[]>([]); useEffect(() => { if (!userId) { setOrders([]); return; } const controller = new AbortController(); fetch(`/api/orders?user=${userId}`, { signal: controller.signal }) .then((r) => r.json()) .then(setOrders) .catch((e) => { if (e.name !== "AbortError") throw e; }); return () => controller.abort(); }, [userId]); return { orders }; }

Case 3: Hooks inside a list

tsx
{items.map((item) => { const [open, setOpen] = useState(false); // one hook per item return <Row key={item.id} open={open} onToggle={() => setOpen(!open)} />; })}

If items changes length, the count changes. Extract a component so each row owns its hooks:

tsx
function Row({ item }: { item: Item }) { const [open, setOpen] = useState(false); return <li onClick={() => setOpen(!open)}>{item.label}{open && item.detail}</li>; } {items.map((item) => <Row key={item.id} item={item} />)}

Case 4: A throw in render, then a retry

tsx
const [data, setData] = useState<Data | null>(null); if (!data) throw fetchData(); // Suspense path useEffect(() => { /* ... */ }, []);

A thrown promise suspends the render; when it resolves React re-renders and now evaluates the skipped code. If the hook count differs between the suspended attempt and the retry, this error appears. Keep hooks above the throw, or use the use() API where the framework version supports it:

tsx
const data = use(dataPromise); // React 19, must be inside Suspense useEffect(() => { trackView(data.id); }, [data.id]);

Case 5: Mode-dependent UI

Splitting the component is cleaner than threading conditions through hooks:

tsx
export function Editor(props: { mode: "edit" | "preview"; doc: Doc }) { return props.mode === "edit" ? <EditView doc={props.doc} /> : <PreviewView doc={props.doc} />; }

EditView keeps its cursor state and PreviewView keeps its scroll state; switching mode unmounts one and mounts the other, which is the intended behavior and cannot desynchronize hook slots.

Case 6: The error inside an error boundary loop

An error boundary that resets by changing a key remounts the subtree. If the reset also changes a prop that flips a conditional hook, the remount renders a different hook count and the boundary catches the same error again, producing a loop. Log error.message and the component name once, then fix the hook order rather than resetting the boundary harder.

Common Compilation/Runtime Mistakes & Version Gotchas

  • ESLint is disabled locally. react-hooks/rules-of-hooks catches this class at lint time. If it is off, the first signal becomes a production error. Enable it with the recommended config rather than per-line disables.
  • React 19 StrictMode double-invokes render. This exposes impure render logic that calls a hook conditionally on the first pass; the count difference is real, not a StrictMode artifact, so fix the hook rather than disabling StrictMode.
  • Fast Refresh keeps state across edits. Adding a hook while the dev server hot-reloads can show this error once even for correct code. A full reload clears it; if it returns immediately after reload, the code is wrong.
  • use is not a normal hook. In React 19 it may be called conditionally in some positions, which makes it look like a counterexample. Everything else still follows the fixed-order rule.
  • Custom hooks must start with use. A helper named fetchUser that calls useState will be inlined into the caller by the compiler's assumptions and violate ordering; the lint rule exists for exactly this case.
  • Suspense boundaries reset children. A boundary that remounts on every navigation resets hook state; that is expected, but it also hides slot mismatches during development, so test the component without the boundary once.

To compare two render sequences from a bug report, paste the console excerpts into the diff tool. For a component that renders server-provided JSON, the JSON formatter makes the shape obvious before it reaches a hook.

Primary references: Rules of Hooks states the ordering requirement, and error #310 documents this message and the early-return cause.

Official references

primary documentation

The React documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit React work — they run entirely in this browser tab, so nothing you paste leaves your device.

All React guides

More in React

All React guides

The guides filed next to this one in React, in library order.