Chapter 14 Β· Escape Hatches
Custom Hooks
When several components need the same stateful logic, package it into your own Hook: a function whose name starts with use.
- What a custom Hook is, and how to extract one
- The naming rule, and why it matters
- Custom Hooks share logic, not state
- Passing values and event handlers to Hooks
- When to write a custom Hook
The problem: duplicated logic
Two components both need to know whether the user is online:
Extracting a custom Hook
The components are now short and say what they want ("am I online?") rather than how to find out.
The naming rule
- Components start with a capital letter and return JSX:
StatusBar. - Hooks start with
use+ a capital letter, and can return anything:useOnlineStatus.
The name use⦠tells you, and the linter, that the function calls other Hooks, so the Rules of Hooks apply: call it only at the top level of a component or another Hook.
use
If a function doesn't call any Hooks, it's just a normal function. Name it getSorted(), not useSorted().
Hooks share logic, not state
This is the key point. Every call to a Hook is completely independent:
It's as if you'd written two useState calls yourself. To share state between components, you still lift it up or use context (Chapters 9 and 11).
Passing reactive values to Hooks
The code inside a custom Hook re-runs on every render of the component that uses it, so it always gets the latest props and state:
A useful example: useLocalStorage
useState(() => ...) runs the function only on the first render. Use it when computing the initial value is expensive, like reading localStorage.
When should you write a custom Hook?
- When you notice the same Effect or state logic in several components.
- When an Effect is complicated and a good name would make the component clearer:
useChatRoom(roomId)is easier to read than 20 lines of Effect. - Keep Hooks focused on one concrete purpose. Avoid generic "lifecycle" Hooks like
useMount(fn), because they hide dependencies.
More examples
Example 1: useToggle
Example 2: useFetch
Example 3: useDebouncedValue
Custom Hooks can be chained: the output of one Hook becomes the input of another.
Example 4: useDocumentTitle
Recap
- A custom Hook is a function named
useSomethingthat calls other Hooks. - It shares stateful logic. Each call has its own independent state.
- It re-runs with the component, so it always sees the latest props and state.
- Extract one when logic repeats, or when a name would make an Effect clearer.
Exercises
1. useCounter
Write useCounter(initial) that returns { count, increment, decrement, reset }. Use it in two separate counters, and check that they're independent.
Show solution
2. useWindowWidth
Write a Hook that returns the current window.innerWidth and updates when the window is resized. Show "π± Mobile" if it's under 600, and "π₯οΈ Desktop" otherwise.
Show solution
3. Hook or not? π’ easy
Show answer
A: it calls no Hooks, so it shouldn't start with use. Rename it to formatDate. B: a correct custom Hook. C: it calls a Hook, so it must be named useUser. Otherwise the linter can't check the Rules of Hooks.
4. Use useToggle π’ easy
Use useToggle (Example 1) three times in one component: dark mode, notifications and sound, each with its own checkbox.
Show solution
Three calls give three independent states. Hooks share logic, not state.
5. useDocumentTitle in your project π’ easy
In sample-test-react, use useDocumentTitle to show "Count: N" in the tab title, where N is your counter's value.
Show solution
6. useKeyPress π‘ medium
Write useKeyPress(key, callback), which calls callback whenever key is pressed anywhere on the page. Use it to increment a counter with the "ArrowUp" key.
Show solution
7. Use useFetch π‘ medium
Using useFetch (Example 2), show the list of users from https://jsonplaceholder.typicode.com/users, and next to it, the details of the selected user from /users/{id}.
Show solution
list.data?.map uses optional chaining: if data is still null, the result is undefined instead of a crash.
8. Debounced search with Hooks π‘ medium
Rebuild the debounced search from Chapter 12 using useDebouncedValue. Compare how much shorter the component is.
Show solution
9. Persist your todo app π‘ medium
Swap useState for useLocalStorage('todos', []) in your todo app from Chapter 8. Refresh the page: the todos should still be there.
Show solution
Because the Hook returns the same [value, setValue] shape, nothing else in the component changes.
10. useCountdown π΄ hard
Move the countdown logic from Chapter 13 (Exercise 10) into useCountdown(start), which returns { seconds, running, start, pause, reset }. Then render two independent timers (10s and 30s) on one page.
Show solution
π Official docs: Reusing Logic with Custom Hooks