Command Palette

Search for a command to run...

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

Fixed: hooks at the top, conditions below

Profile calls the same two hooks on every render. Tabs appears only after logging in, and that's allowed: its hook belongs to Tabs, not to Profile.

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?

Fixed: hooks at the top, conditions below

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

Profile rendered, loggedIn = false likes = 0
Profile rendered, loggedIn = true likes = 0
Profile rendered, loggedIn = true likes = 1