Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Routing and Application Architecture
Stage 5: Specialization (pick ONE)

Part 07 / Topic 4 of 6

The rules of hooks

React keeps track of each component's hooks by call order, not by name - render after render, it expects "this component's 1st hook call is this state, its 2nd is that effect," in that exact sequence. Two rules keep that order stable:

  1. Only call hooks at the top level of a component or another hook - never inside an if, a loop, or after an early return.
  2. Only call hooks from a React function component or a custom hook - never from a plain helper function or a class method.

examples/04_rules_of_hooks_violation.jsx's ConditionalProductCardBroken breaks rule 1 on purpose:

// examples/04_rules_of_hooks_violation.jsx (broken, trimmed)
export function ConditionalProductCardBroken({ showDiscount }) {
  if (showDiscount) {
    const [discount] = useState(10);
    const [quantity] = useState(1);
    return <p>Discount: {discount}% - Qty: {quantity}</p>;
  }
  const [quantity] = useState(1);
  return <p>No discount - Qty: {quantity}</p>;
}

When showDiscount is true, quantity's useState call is this component's 2nd hook call. When it is false, quantity's call is the 1st - a different slot, as far as React's internal bookkeeping goes, holding onto whatever the 1st slot held in the previous render. Mounting with showDiscount={true} and rerendering with showDiscount={false} really throws (examples/04_rules_of_hooks_violation.test.jsx):

Rendered fewer hooks than expected. This may be caused by an accidental early return statement.

ConditionalProductCardFixed calls both useState hooks unconditionally, every render, and only branches in the JSX it returns - the fix is always to move the condition below every hook call, never around one of them. The identical prop change on the fixed version really never throws.

๐Ÿ” Going deeper: oxlint's react/rules-of-hooks rule (configured in this repo's .oxlintrc.json) catches exactly this mistake statically, before the code ever runs - examples/04_rules_of_hooks_violation.jsx silences it, line by line, with a comment explaining why (see the file). A single conditional hook call with nothing after it in the same component sometimes does not crash at all - React only detects the mismatch once there is a second hook call whose slot shifts, which is why the broken example above deliberately has two.

Done here? The practice set for Part 7 โ€” including the solutions โ€” is on the part page.

Search the guide