Sub topic 15
Pitfalls and when a plain function is enough
This chapter assumes you have read the earlier chapters on the Rules of Hooks, effects with cleanup, dependency arrays, and useCallback. It collects the mistakes that show up most often in custom hooks. It also gives a way to decide whether you need a hook at all.
A hook is for logic that uses React
A custom hook is a function whose name starts with use and that calls other hooks. The second part is what matters. If a function calls no hook, React gains nothing from treating it as one.
// Looks like a hook, but calls no hook.
export function useFormatPrice(cents, currency) {
return new Intl.NumberFormat('en-US', { style: 'currency', currency }).format(cents / 100);
}This function has no state, no effect and no context. Renaming it formatPrice costs nothing and has several benefits:
- You can call it inside loops, callbacks, and conditions, where the Rules of Hooks forbid hook calls.
- You can call it from non-React code, such as a server script or a utility module.
- You can test it with a plain function call, with no
renderHook. - Readers know it cannot hold state or run effects.
Use this test. If you remove every use* call from the body and the function still does its job, it should be a plain function.
export function formatPrice(cents, currency) {
return new Intl.NumberFormat('en-US', { style: 'currency', currency }).format(cents / 100);
}The same applies to calculations on props or state. Filtering a list is a plain function of its inputs.
export function filterTodos(todos, filter) {
return todos.filter((todo) => (filter === 'done' ? todo.done : !todo.done));
}Call it during render: const visible = filterTodos(todos, filter);. Add useMemo only after you measure that the computation is slow.
Common pitfalls
Expecting hooks to share state
Two components that call useToggle() each get their own state. This was the point of the earlier chapter on isolation. The pitfall appears when a developer writes useCart() and expects every component to see the same cart.
A hook shares logic, not state. For shared state, put the state in one place and read it from many:
- Lift the state to a common parent and pass it down.
- Provide it through context, and have the hook read the context with
useContext. - Keep it in an external store and read it with
useSyncExternalStore.
The hook then becomes a thin reader over that single source.
Returning unstable objects and functions
Effects compare their dependencies with Object.is. A new object, array, or function on every render counts as a change every time. The next hook has this problem.
import { useEffect, useState } from 'react';
// Pitfall: `options` is a new object on every render.
export function useSearch(query, options) {
const [results, setResults] = useState([]);
useEffect(() => {
fetch(`/api/search?q=${encodeURIComponent(query)}&limit=${options.limit}`)
.then((res) => res.json())
.then(setResults);
}, [query, options]);
return results;
}A caller who writes useSearch(text, { limit: 10 }) creates a new object on each render. The effect runs after every render, calls setResults, which triggers a render, which creates a new object. The result is a request loop.
Prefer primitive parameters, which compare by value.
import { useEffect, useState } from 'react';
export function useSearch(query, limit = 10) {
const [results, setResults] = useState([]);
useEffect(() => {
let ignore = false;
fetch(`/api/search?q=${encodeURIComponent(query)}&limit=${limit}`)
.then((res) => res.json())
.then((data) => {
if (!ignore) setResults(data);
});
return () => {
ignore = true;
};
}, [query, limit]);
return results;
}The same rule applies to what a hook returns. If callers may put a returned function or object in their own dependency array, keep it stable with useCallback or useMemo. If callers pass a callback in, read it through a ref as in useEventListener, so they do not have to memoize it.
Silencing the lint rule
When the exhaustive-deps rule complains, the usual cause is a real problem. An // eslint-disable-next-line comment hides a stale closure. It does not fix it. Try these fixes in order:
- Move the value or function inside the effect, so it is no longer a dependency.
- Move values that never change out of the component or hook, to module level.
- Use a functional update, such as
setCount((c) => c + 1), so the effect does not read state. - Read the latest callback through a ref when the effect must not restart.
Disable the rule only when you can state why the omitted value is safe to ignore, and put that reason in a comment.
Wrapping effects in lifecycle helpers
Hooks such as useMount look convenient and cause trouble.
import { useEffect } from 'react';
// Pitfall: hides the dependency array from the linter.
export function useMount(fn) {
useEffect(() => {
fn();
}, []);
}The linter cannot see which values fn uses, so it cannot warn about stale ones. The wrapper also drops any cleanup function that fn returns. React components do not have a "mount" event in the way class components did. Effects describe synchronization with something outside React, and each effect should say what it synchronizes and with what. A hook named after the job, such as useDocumentTitle(title) or useOnlineStatus(), keeps that information. A hook named after a timing slot loses it.
Using an effect to compute derived state
This pattern renders twice and can show stale data for a frame.
import { useEffect, useState } from 'react';
// Pitfall: the effect copies derived data into state.
export function useVisibleTodos(todos, filter) {
const [visible, setVisible] = useState([]);
useEffect(() => {
setVisible(todos.filter((todo) => (filter === 'done' ? todo.done : !todo.done)));
}, [todos, filter]);
return visible;
}The render runs with the old visible, then the effect updates it, then React renders again. If a value can be computed from props and state, compute it during render. That is the filterTodos function from earlier, and it needs no hook.
Effects are for synchronizing with systems outside React: timers, network, the DOM, subscriptions. Reactions to a user action, such as submitting a form, belong in the event handler.
Calling hooks conditionally
The Rules of Hooks apply inside custom hooks too. The following code breaks them.
import { useState, useEffect } from 'react';
// Pitfall: the hook calls depend on `enabled`.
export function useUserName(id, enabled) {
if (!enabled) return null;
const [name, setName] = useState(null);
useEffect(() => {
fetch(`/api/users/${id}`)
.then((res) => res.json())
.then((user) => setName(user.name));
}, [id]);
return name;
}The early return means the number of hook calls changes between renders, and React loses track of which state belongs to which call. Call every hook on every render. Put the condition inside the effect instead: if (!enabled) return; as the first line, and add enabled to the dependencies. If the condition decides whether a whole component needs the logic at all, split it into a child component that always calls the hook.
Hiding too much in one hook
A hook that fetches, caches, retries, formats, and tracks form state is hard to test and hard to change. A hook with ten parameters and a return object with fifteen fields is the same problem in another form. Split it along the seams you already see. Small hooks compose well, and the earlier chapter on composing hooks showed how. Return only what callers need, and keep the parameter list short.
Should this be a hook?
Quick reference
| Symptom | Likely cause | Fix |
|---|---|---|
| Effect runs after every render | Object, array, or function in dependencies is recreated each render | Pass primitives, or stabilize with `useMemo`, `useCallback`, or a ref |
| Handler sees old values | Stale closure from a missing dependency | Add the dependency, or read the latest value through a ref |
| Two components do not see the same data | Each hook call has its own state | Lift state, use context, or use an external store |
| "Rendered more hooks than during the previous render" | Hook called after an early return or inside a condition | Call hooks unconditionally and move the condition into the hook body |
| Flash of stale data, double render | Derived value stored in state through an effect | Compute during render |
| Hook is hard to test or reuse | One hook does too many jobs | Split it into smaller hooks |
Exercises
Exercise
A teammate wrote function useClamp(value, min, max) { return Math.min(Math.max(value, min), max); } and uses it in three components. Should it stay a hook? Explain, and give the better form.
Show answer
No. It calls no hook, so it needs no use prefix. Rename it to clamp, which makes it callable in event handlers, loops, and tests without React. Components call it during render: const width = clamp(raw, 0, 100);.
Exercise
useSearch(query, { limit: 10 }) has options in its effect's dependency array, and the component sends requests in an endless loop. Give two ways to fix it.
Show answer
The object literal is recreated on every render, so the effect sees a change each time. First, change the signature to take primitives, useSearch(query, limit), and depend on [query, limit]. Second, keep the object parameter but have the caller create it once, outside the component or with useMemo. The first option is easier to use correctly, because callers cannot get it wrong.