Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 10.2 — Useful Hook Recipes
React · Example 1 of 5

useToggle and usePrevious

Two toggles in one go cancel out, as they should, because toggle uses an updater. usePrevious remembers the price before the last change.

Seven small hooks cover jobs almost every app has: useToggle, useLocalStorage, useDebounce, useOnlineStatus, useMediaQuery, usePrevious and useInterval; building them yourself teaches the patterns behind every hook library.

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

Write useCounter as a recipe: useCounter({ min = 0, max = 10 } = {}) returns { count, inc, dec } and never leaves the range.

02

Write useWindowWidth() that returns window.innerWidth and updates on resize, with cleanup.

03

Use useDebounce and useLocalStorage together: a notes textarea that saves its text 500 ms after the user stops typing.

Explain it without notes

01

How does useDebounce make sure only the last value is used?

02

Why does useLocalStorage read storage in a lazy initialiser and write in an effect?

03

Why is a naive useInterval either stale or constantly restarting, and how does useEffectEvent fix it?

04

What is the difference between the ref-based and the state-based usePrevious?

useToggle and usePrevious

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

help shown: false
Price: 105 up from 100
Price: 85 down from 105