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.

Introduction & Quick Summary
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.
| Message | Meaning | Typical line |
|---|---|---|
| Rendered more hooks | New hook with no matching slot | Hook after a conditional return |
| Rendered fewer hooks | Skipped a hook that ran before | Return placed between hooks |
| Invalid hook call | Hook called outside a component | Helper function or event handler |
| Cannot update a component while rendering | State write during render | setState 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:
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:
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:
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
| Pattern | Hooks per render | React result |
|---|---|---|
| Early return before hooks | 0 then 1 | Rendered more hooks |
| Early return between hooks | 2 then 1 | Rendered fewer hooks |
Hook inside if | 1 or 0 | Both errors, depending on order |
Hook inside map | Variable | More or fewer hooks |
| Hook in a custom hook after a return | Variable | Same errors, longer stack |
Hook in a try after a throw | Variable | More hooks on retry |
| All hooks at top, output gated | Constant | No error |
| Fix | Preserves state | Best for |
|---|---|---|
| Move hooks above all returns | Yes | Most components |
| Split into two components | Yes, per component | Modes with different data |
Pass undefined and no-op in effects | Yes | Fetches and subscriptions |
| Render a keyed child | Resets child state | Switching between records |
Add react-hooks/rules-of-hooks | n/a | Preventing regressions |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
Case 1: Feature flag adds a hook
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:
useEffect(() => {
if (!flags.autosave) return;
save(draft);
}, [draft, flags.autosave]);Case 2: Custom hooks that return early
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:
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
{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:
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
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:
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:
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-hookscatches 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.
useis 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 namedfetchUserthat callsuseStatewill 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 documentationThe React documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit React work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related React guides
All React guidesReact 19: Support for defaultProps will be removed
React 19 ignores defaultProps on function components, so a default becomes undefined. Move defaults into the parameter list and handle null honestly.
React: Each child in a list should have a unique key prop
Keys tell React which item is which between renders. Use stable ids, avoid index keys and put the key on the mapped element, not on a wrapper.
react-hook-form with zod 4: resolver type errors after the upgrade
Zod 4 split input from output and resolvers v5 re-typed Resolver. Drop the generic, or pass all three, and the errors disappear.
React Profiler API: Measuring Render Timings and Identifying Wasted Re-Renders
actualDuration versus baseDuration, phase names that tell you who triggered a commit, and how to ship the numbers without flooding a backend.
More in React
All React guidesThe guides filed next to this one in React, in library order.