Command Palette

Search for a command to run...

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

Returning values and functions: a form field hook

Click into a field and leave it empty to see its error. Each useField call has its own value and touched flag, and the component only uses what the hook returns.

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?

Returning values and functions: a form field hook

Preview

Press Run to see the page.

Console

Nothing logged yet.