Sub topic 13
Packaging effects into custom hooks
What this chapter assumes
You should already be comfortable with useState, useEffect, dependency arrays and cleanup functions. You should also know how to fetch data in an effect and abort it on cleanup. This chapter shows how to move that code out of components and into reusable functions called custom hooks.
Why extract an effect
An effect often has three parts that belong together: some state, the effect that updates it, and the cleanup that undoes it. When the same trio shows up in several components, copying it creates two problems. Every copy must be fixed when you find a bug, and each component is cluttered with plumbing that has nothing to do with what it displays.
A custom hook is a JavaScript function that:
- has a name starting with
use - calls other hooks, such as
useStateoruseEffect, at its top level - returns whatever the component needs (a value, an object, an array, or nothing)
React gives custom hooks no special treatment. The use prefix tells you and the linter that the function follows the rules of hooks. The linter can then check that it is called unconditionally and that its effects list the right dependencies.
Example: a subscription hook
Here is the window-width logic from the earlier chapter on listeners, written as a hook.
import { useEffect, useState } from 'react';
export 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;
}
export function Layout() {
const width = useWindowWidth();
return <p>{width < 600 ? 'Mobile layout' : 'Desktop layout'}</p>;
}Layout now says what it needs ("the window width") and not how to get it. The listener, its cleanup and the state live in one place.
The initial window.innerWidth read assumes a browser. If the same code is rendered on a server, window does not exist and the call throws. In that case, start from a fixed default such as 0 and set the real width inside the effect.
Each call gets its own state
A custom hook shares logic, not state. Every component that calls useWindowWidth() gets its own useState value and its own listener.
This is usually what you want, because each component re-renders only for its own state. It also explains what a hook cannot do. If two components must see the same value and stay in sync, such as a logged-in user, the hook is not enough. You need state lifted to a common parent, context, or an external store.
Example: a data-fetching hook
The data-fetching effect from the earlier chapter is a good candidate. It uses AbortController to avoid stale responses, which is easy to forget when copying code by hand. Putting it in a hook makes the correct version the default.
import { useEffect, useState } from 'react';
export function useFetch(url) {
const [state, setState] = useState({
data: null,
error: null,
loading: true,
});
useEffect(() => {
const controller = new AbortController();
setState({ data: null, error: null, loading: true });
fetch(url, { signal: controller.signal })
.then((res) => {
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
})
.then((data) => setState({ data, error: null, loading: false }))
.catch((error) => {
if (error.name !== 'AbortError') {
setState({ data: null, error, loading: false });
}
});
return () => controller.abort();
}, [url]);
return state;
}
export function User({ userId }) {
const { data, error, loading } = useFetch(`/api/users/${userId}`);
if (loading) return <p>Loading...</p>;
if (error) return <p>Failed to load: {error.message}</p>;
return <h1>{data.name}</h1>;
}Three details matter here:
- The hook's only dependency is
url, a string, so it compares by value and does not cause extra runs. - The three pieces of state live in one object and change together. This avoids a render where
loadingisfalsebutdatais stillnull. Userhas no effect of its own. All the synchronization is inside the hook.
Designing the interface
A hook's parameters and return value form its public interface. A few guidelines keep it easy to use.
Parameters become dependencies
Anything the hook's effect reads from its parameters must appear in the dependency array. The caller therefore controls when the effect re-runs by changing the arguments. Prefer primitive arguments (strings, numbers, booleans). They compare by value, so a caller cannot trigger extra runs by accident.
import { useEffect } from 'react';
export function useDocumentTitle(title) {
useEffect(() => {
const previous = document.title;
document.title = title;
return () => {
document.title = previous;
};
}, [title]);
}Objects and functions as arguments
If a hook accepts an object or function and lists it as a dependency, a caller who writes it inline creates a new value on every render. The effect then re-runs every time. You have three options:
- Accept primitives and build the object inside the effect.
- Document that callers must memoize the argument with
useMemooruseCallback. - Read the latest function without making it a dependency. A later chapter covers this technique.
What to return
Return the smallest useful value. A single value suits useWindowWidth. Several related values suit an object, as in useFetch. An array of two items suits hooks that mimic useState, so callers can rename the items freely. Make sure that the returned values are stable if callers will put them in their own dependency arrays.
Custom hook, component or plain function
| You need to share | Use | Reason |
|---|---|---|
| Logic that calls hooks (state, effects) | Custom hook | Only components and hooks may call hooks |
| Logic with no hooks, such as formatting a date | Plain function | No need for the `use` prefix |
| Markup together with logic | Component | A hook cannot return JSX that manages its own placement in the tree |
| State that several components must share | Context or a common parent | Each hook call has independent state |
Common errors
- Missing
useprefix. A function namedfetchDatathat callsuseStateworks at runtime, but the linter will not check its hook calls. Name ituseFetchData. - Calling a hook conditionally.
if (enabled) { useFetch(url); }breaks the rule that hooks run in the same order on every render. Pass a flag to the hook and skip the work inside its effect instead. - Lifecycle wrappers. A hook like
useOnMount(fn)that wrapsuseEffect(fn, [])hides the dependencies. The linter can no longer see whatfnreads, so stale values slip through. Prefer a hook named for what it synchronizes, such asuseWindowWidth. - Hiding too much. A hook that takes ten options and does five unrelated things is harder to read than the effects it replaced. Extract when the code has a clear name and a clear purpose, not just to shorten a component.
- Expecting shared state. If two components call a hook and show different values, that is working as designed.
Summary
A custom hook packages related state and effects behind a named function, so components stay focused on rendering. Each call gets its own state. Parameters become dependencies, so prefer primitives and keep the effect's dependency array honest.
Exercise
Write a custom hook useOnlineStatus that returns true when the browser is online and false when it is offline. It must update when the browser fires the online and offline events, and it must clean up. If two components call it, how many listeners are registered for each event?
Show answer
Initialize state from navigator.onLine. In an effect with an empty dependency array, add online and offline listeners on window that set the state to true and false. Return a cleanup that removes both. For example: function useOnlineStatus() { const [online, setOnline] = useState(navigator.onLine); useEffect(() => { const on = () => setOnline(true); const off = () => setOnline(false); window.addEventListener('online', on); window.addEventListener('offline', off); return () => { window.removeEventListener('online', on); window.removeEventListener('offline', off); }; }, []); return online; }. The empty array is correct because the effect reads no props or state. Two components that call the hook register two listeners for each event, one pair per call. This is because each call has its own state and effect.
Exercise
A teammate writes useInterval(callback, delay) and inside it uses useEffect(() => { const id = setInterval(callback, delay); return () => clearInterval(id); }, [callback, delay]);. A component calls it as useInterval(() => setCount((c) => c + 1), 1000). What goes wrong, and what are two ways to fix it?
Show answer
The inline arrow function is a new object on every render, so callback changes each time. The effect cleans up and restarts the interval on every render. If renders happen more often than once a second, the interval may never fire. One fix is for the caller to wrap the callback in useCallback with a stable dependency list. Another fix is to design the hook to avoid the dependency, for example by storing the latest callback in a ref and reading it from inside the interval, so only delay is a dependency.