Sub topic 13
Packaging effects into custom hooks
This chapter assumes you can write useEffect with a dependency array and a cleanup function, and that you have seen the window resize and data fetching examples from earlier chapters.
What a custom hook is
A custom hook is a JavaScript function whose name starts with use and that calls other hooks. Moving an effect into one gives the logic a name, hides the setup and cleanup, and lets many components reuse it.
Each component that calls a custom hook gets its own state. Hooks share logic, not data.
Example: a window width hook
The resize listener from earlier already works as a hook. The component only sees a number.
import { useEffect, useState } from 'react';
function useWindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
function handleResize() {
setWidth(window.innerWidth);
}
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return width;
}
function Layout() {
const width = useWindowWidth();
return <p>{width < 600 ? 'Narrow' : 'Wide'} layout</p>;
}Any component can call useWindowWidth(). Each call registers and removes its own listener.
Example: a data fetching hook
The User component mixes two jobs: loading data and showing it. A hook separates them. The arguments of the hook become the effect's dependencies.
import { useEffect, useState } from 'react';
function useUser(userId) {
const [user, setUser] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
const controller = new AbortController();
setUser(null);
setError(null);
fetch(`/api/users/${userId}`, { signal: controller.signal })
.then((res) => {
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
})
.then(setUser)
.catch((err) => {
if (err.name !== 'AbortError') setError(err);
});
return () => controller.abort();
}, [userId]);
return { user, error };
}
function User({ userId }) {
const { user, error } = useUser(userId);
if (error) return <p>Failed to load: {error.message}</p>;
if (!user) return <p>Loading...</p>;
return <h1>{user.name}</h1>;
}The race condition protection travels with the hook. Every component that uses useUser gets it without extra work.
Rules and pitfalls
- Prefer primitive arguments. A hook that takes an object or function as an argument gets an unstable dependency if the caller creates a new one on every render. Pass
userId, not{ id: userId }, or document that callers must memoize. - Name hooks by purpose.
useWindowWidthanduseUsersay what they do. A hook likeuseMount(fn)hides the dependencies and invites stale closures. - Do not wrap for its own sake. If the effect is used once and is short, leaving it in the component is fine. Extract when you reuse it, or when the component reads better without it.
- Keep the effect honest. Moving code into a hook does not change the rules. It still needs correct dependencies and cleanup, and it still runs twice under Strict Mode in development.
Exercise
You write function useInterval(callback, delay) that calls setInterval(callback, delay) inside an effect with the dependencies [callback, delay]. A component passes a new inline arrow function as callback on every render. What goes wrong, and what is one way to fix it?
Show answer
The new function changes the callback dependency on every render, so the effect cleans up and restarts the interval each time. If the component re-renders more often than delay, the callback may never fire. One fix is to have callers wrap the callback in useCallback. Another is to avoid the dependency, for example by having the hook design take primitive arguments only, as in the Timer example that uses setSeconds((s) => s + 1) with an empty dependency array.