React · Chapter 20 of 26
Custom hooks
By the end of this chapter you can move logic that uses hooks out of a component into a function of your own whose name starts with use, reuse it in many components, explain why each component that calls it gets its own state, follow the rules of hooks and read their errors, and turn chapter 16's fetching into one hook. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.
- Part: Effects and data
- 4 tasks
- React
- In the all labs plan
The first 2 chapters of React are free. This one comes with the all labs plan.
Why you need this
Look at what Parda's pages have grown. The shows page, the show details and the venues list each have the same twenty-odd lines: state for the data, the error and the loading line, an effect with chapter 17's cleanup, a retry count. Three copies, and when Rukhsana fixed a race in one, the other two still had it. The seat page and the checkout both count down the 10-minute seat hold. Every dialog Ira designed closes on Escape, and each one adds and removes its own key listener.
A plain helper function cannot hold this logic, because the logic is made of hooks: useState, useEffect, useContext. And hooks may only be called from components. Except for one more place: a function of your own whose name starts with use, called from a component. That is a custom hook, and it is how React code shares logic.
What you build: 4 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
useHoldTimer.js: the seat hold timer
Write the hook useHoldTimer(seconds), the default export of useHoldTimer.js. It returns an object { left, expired }: left is the seconds left, seconds at first and then one fewer every second (a timer of 1000 ms); expired is false, and true once left reaches 0. left stops at 0, and then no timer of the hook may be left running. When the component using the hook goes away, clear its timer too.
Two components that call it each get their own timer: the Check renders, in StrictMode with fake timers, one component with useHoldTimer(600) and one with useHoldTimer(3). After 1 second they must return 599 and 2, after 3 seconds the second must return left 0 and expired true, and after 5 seconds 595 and still 0. Then it removes both (no timer may be left), and checks that useHoldTimer(2) leaves no timer running once it reaches 0. Remove the starter's todo line, which only tells App.jsx to show this task's slot.
- Task 2
useKeyPress.js: a hook for one key
Write the hook useKeyPress(key, handler), the default export of useKeyPress.js. While the component that calls it is on the page, a keydown on window whose key is key (like Escape) calls handler once, with the event. Other keys call nothing. When the component goes away, remove the listener. When the component renders with a new handler or a new key, the next press must use the new ones, never the old.
The Check renders a component in StrictMode with useKeyPress('Escape', handler) and counts the calls: one press of Escape must call the handler exactly once (a listener that StrictMode's first run left behind would call it twice); a press of a calls nothing; after a render with a new handler, Escape calls only the new one; after a render with the key Enter, Escape calls nothing and Enter calls the handler once; after the component goes away, Enter calls nothing.
- Task 3
useFetch.js: chapter 16's fetching, as a hook
Write the hook useFetch(load, deps), the default export of useFetch.js. load is a function that starts a request and returns its promise, like () => getShow(id); deps is an array of the values that mean load again, like [id]. Call load() when the component appears and whenever a value in deps changes, and return an object { data, error, loading, retry }: data is what load's promise gave, or null before that; error is the error's message if it failed, or null; loading is true while a request runs and false after it; retry is a function that calls load() again.
An answer from an old request (deps changed since, or the component went away) must change nothing, not even when it fails. load is a new function on every render, so it is not a dependency: deps are. The Check renders a component in StrictMode that calls useFetch(() => load(id), [id]) and answers the requests itself: it checks loading, data and error before and after answers, changes id and answers the old request last (it must be ignored), lets an old request fail late (no error may show), makes a request fail with The server is busy. Try again. (error must be that message and loading false), then clicks a button that calls retry() (load must be called again, loading true, then the new data).
- Task 4 · interview question
Interview: useCart.js, the basket the header cannot see
The header's count and the basket both call useCart(), which returns { items, add, remove }. The bug: in the Preview, add a ticket with + Ghar Wapsi Express; the basket shows it, but the header still says Basket (0). Fix useCart, the default export of useCart.js, so that every component that calls it inside one CartProvider gets the same cart: the value CartProvider gives through CartContext (both in CartContext.jsx), { items, add, remove }. Then an add from one component shows in all.
Outside any CartProvider, CartContext gives null, and useCart must throw an error with exactly the message useCart must be used inside CartProvider. The Check renders three components that use useCart inside a CartProvider of its own: one adds a ticket, and the other two must see it; Remove must take it out again. Then it renders one outside any provider, and expects that error.
Rukhsana will ask: do two components that use the same hook share its state?
What you will learn
- A custom hook: a function named use... that calls hooks, and returns whatever you like.
- It shares logic, not state: each component that calls it gets its own state.
- The rules of hooks: call them at the top level of a component or a custom hook, never inside a condition or after an early return; the errors when you do not.
- Extracting a hook from a component, step by step.
- useFetch: chapter 16's loading, data, error and retry, written once, and why its load function is not a dependency.
More in Effects and data
Build "Custom hooks" yourself
Parda sells tickets for Pune's own cinemas and stages, and its booking page broke on opening night. You rebuild it in React. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.
The first 2 chapters of React are free. This one comes with the all labs plan.