Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 4.3 — The Rules of Hooks
React · Example 2 of 3

A conditional hook in real React

The first render calls two hooks. After the click, the if is true and the render calls three. React prints a table of the hook order, then throws. The page goes blank because nothing caught the error (error boundaries come in Topic 14.5).

Call hooks only at the top level of a component or a custom hook, never inside conditions, loops, nested functions or after an early return, because React matches each hook to its saved state purely by the order of the calls.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

This component breaks the rules. Rewrite it correctly: ``jsx function Price({ amount }) { if (amount === 0) return <p>Free</p>; const [showTax, setShowTax] = useState(false); return <p onClick={() => setShowTax(!showTax)}>{showTax ? amount * 1.18 : amount}</p>; }

02

A Comments section should have its own useState for the new comment text, but only appear when open is true. Show the correct structure.

Explain it without notes

01

State the two Rules of Hooks.

02

Why does React need hooks to be called in the same order on every render?

03

How do you fix a hook that only needs to run in some situations?

04

What does eslint-plugin-react-hooks do?

A conditional hook in real React

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

Profile rendered, loggedIn = false likes = 0
React has detected a change in the order of Hooks called by Profile. This will lead to bugs and errors if not fixed. For more information, read the Rules of Hooks: https://react.dev/link/rules-of-hooks

   Previous render            Next render
   ------------------------------------------------------
1. useState                   useState
2. useState                   useState
3. undefined                  useState
   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Uncaught Error: Rendered more hooks than during the previous render.
An error occurred in the <Profile> component.

Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://react.dev/link/error-boundaries to learn more about error boundaries.