ReactMedium

What is hook call order?

React identifies each hook by the order in which it is called during a component's render, not by name. On every render the component must call the same hooks in the same order, so the first useState always maps to the first state slot, the second to the second, and so on.

How React stores hooks

Each component instance (fiber) has a linked list of hook states. During render, React walks the list as your code calls hooks: useState number 1 reads slot 1, useEffect number 2 reads slot 2. There are no names or keys involved.

What breaks the order

  • Calling a hook inside an if, loop or switch.
  • An early return before some hooks.
  • Calling hooks inside nested functions or event handlers.
  • Calling hooks a variable number of times (in a .map()).

If a hook is skipped, every later hook reads another hook's state. React detects some of this and throws "Rendered fewer hooks than expected" or warns that the order changed.

The use exception

React 19's use(promise) and use(context) can be called conditionally because they do not store state in the hook list.

How to write conditional logic correctly

  • Call all hooks at the top, then branch in JSX.
  • Put conditions inside effects: useEffect(() => { if (!enabled) return; ... }).
  • Extract a child component and render it conditionally; its hooks belong to its own instance.
  • For a dynamic number of items, render a component per item.

Code example

tsx
1import { useEffect, useState } from "react";
2
3export function Order({ showCoupon }: { showCoupon: boolean }) {
4 // Render 1 (showCoupon = true): slot1 useState(qty), slot2 useState(coupon), slot3 useEffect
5 // Render 2 (showCoupon = false): if useState(coupon) were inside `if`, slot2 would be the effect -> broken
6
7 // Wrong:
8 // const [qty, setQty] = useState(1);
9 // if (showCoupon) { const [coupon, setCoupon] = useState(""); }
10 // useEffect(() => {}, [qty]);
11
12 // Right: same order every render
13 const [qty, setQty] = useState(1);
14 const [coupon, setCoupon] = useState("");
15 useEffect(() => {
16 document.title = `Qty ${qty}`;
17 }, [qty]);
18
19 return (
20 <div>
21 <input type="number" value={qty} onChange={(e) => setQty(+e.target.value)} />
22 {showCoupon && <input value={coupon} onChange={(e) => setCoupon(e.target.value)} placeholder="Coupon" />}
23 </div>
24 );
25}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app