Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 10.1 — Custom Hooks: Reusing Logic
React · Example 2 of 3

Passing a reactive value into a hook

The first line comes from the first render. Three clicks bring unread to 0. The fourth click sets 0 again, the title string is the same, so the effect doesn't re-run: no fifth line.

A custom hook is a function whose name starts with use and that calls other hooks; it lets many components share stateful logic, while every component that calls it still gets its own separate state.

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 a hook useCharacterCount(text, max) that returns { count, left, tooLong } and use it under a textarea.

02

Extract a useHover() hook that returns [hovered, { onMouseEnter, onMouseLeave }] and use it on two cards that each show Hovered! independently.

03

This component repeats logic twice. Extract a hook and rewrite it: two checkboxes, each with const [x, setX] = useState(false) and an onChange={() => setX(!x)}.

Explain it without notes

01

What is a custom hook, and what makes a function one?

02

If two components call the same custom hook, do they share state? Explain why.

03

Why must custom hook names start with use?

04

How do you pass changing data into a custom hook, and how does the hook react when it changes?

Passing a reactive value into a hook

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

title set to: (3) Inbox
title set to: (2) Inbox
title set to: (1) Inbox
title set to: Inbox