Command Palette

Search for a command to run...

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

A tiny imitation of how React stores hooks

On the second render city reads slot 1, which holds the nickname. Real React is more careful: it notices the number of hooks changed and throws instead of silently mixing values.

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 tiny imitation of how React stores hooks

Console

(nothing was printed)

Expected console output

{ name: 'Asha', city: 'Pune' }
slots: [ 'Asha', 'Ash', 'Pune' ]
{ name: 'Asha', city: 'Ash' }