Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 10.6 — Designing Good Hooks
React · Example 2 of 3

useMount hides a bug that useChatRoom avoids

After switching, the screen says "music" but the useMount connection is still in "general". The purpose hook left general and joined music.

A good hook is named after what it does (useChatRoom, not useMount), takes clear inputs (an options object when there are several), returns stable values and functions so callers' effects don't re-run, and exists only when it actually uses hooks and hides real complexity.

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 6 hands-on exercises with automatic checks.

Practice questions

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

01

Rewrite useMount(() => { document.title = title; }) as a purpose hook that stays correct when title changes.

02

This hook returns a new object every render: function useCart() { const [items, setItems] = useState([]); return { items, add: (i) => setItems((x) => [...x, i]) }; }. Make its return value stable.

03

Turn useFilter(list, "name", true, "asc") into an options-object API and write the hook.

Explain it without notes

01

Why are hooks like useMount considered an anti-pattern?

02

What does it mean for a hook to return stable values, and why do callers care?

03

When should a hook take an options object, and how do you avoid dependency problems with it?

04

How do you decide whether to write a custom hook at all?

useMount hides a bug that useChatRoom avoids

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

useMount: connected to general
useChatRoom: connected to general
useChatRoom: left general
useChatRoom: connected to music