Command Palette

Search for a command to run...

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

useLocalStorage: state that survives a reload

The saved "dark" was read in the lazy initialiser, so the first render was already dark. Strings are stored with their quotes because the hook stores JSON. Hectal's preview keeps localStorage in memory, so it resets on each Run.

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?

useLocalStorage: state that survives a reload

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

on load: Theme: dark, size: 16px
saved theme: "light"
saved size: 18