Sub topic 15
Pitfalls and when a plain function is enough
This chapter assumes you know the Rules of Hooks, useState, useEffect, and how closures capture values. It covers the mistakes that appear most often in custom hooks. It also gives a test for deciding whether you need a hook at all.
Does it need to be a hook?
A custom hook exists so that you can call other hooks, such as useState, useEffect, or useRef, in a reusable unit. If the code calls no hooks, a plain function is simpler. A plain function can be called from anywhere, including loops, conditions, event handlers, and tests, and it needs no use prefix.
export function formatPrice(cents, currency = 'USD') {
return new Intl.NumberFormat('en-US', { style: 'currency', currency }).format(cents / 100);
}Wrapping this in useFormattedPrice adds nothing. It also stops you from calling it inside a .map() callback, where hooks are not allowed.
Common pitfalls
| Pitfall | What goes wrong | Fix |
|---|---|---|
| Hook called conditionally or in a loop | React loses track of which state belongs to which call | Call hooks at the top level; put the condition inside the hook |
| Object or array literal in a dependency array | The value is new on every render, so the effect re-runs every time | Depend on primitive fields, or memoize the value |
| Missing dependency | The effect reads a stale value from an old render | Include every reactive value the effect reads |
| Returning a new function each render | Memoized children and effects that depend on it re-run | Wrap it in `useCallback` when callers may depend on it |
| Expecting shared state | Two components calling the same hook each get their own state | Lift state up or use context or a store |
| Vague "lifecycle" hooks such as `useMount` | The hook hides which values the effect depends on | Name hooks after what they do, such as `useOnlineStatus` |
| Hook that does too much | Hard to test, name, and reuse | Split it into smaller hooks and compose them |
Unstable dependencies
The most common bug is passing an options object. Callers write useSearch(query, { limit: 10 }), which creates a new object on every render. If the hook puts options in its dependency array, the request restarts after every render. Destructure the primitive values inside the hook instead.
import { useState, useEffect } from 'react';
export function useSearch(query, { limit = 10 } = {}) {
const [results, setResults] = useState([]);
useEffect(() => {
const controller = new AbortController();
const url = `/api/search?q=${encodeURIComponent(query)}&limit=${limit}`;
fetch(url, { signal: controller.signal })
.then((res) => res.json())
.then(setResults)
.catch((error) => {
if (error.name !== 'AbortError') console.error(error);
});
return () => controller.abort();
}, [query, limit]);
return results;
}The dependency array lists query and limit, which are strings and numbers. They compare equal across renders unless their values really change.
Signs that a hook is the wrong tool
- It calls no hooks. Make it a plain function.
- It is used in one component and is short. Inline code is easier to follow than a file you must open.
- It wraps a single built-in hook with no added logic. For example,
useCountthat only returnsuseState(0)adds a name and nothing else. - Its name needs "and". A hook called
useUserAndThemeis probably two hooks. - It needs to run conditionally. Extract the non-hook part as a function and keep the hook call unconditional.
A hook should earn its place by hiding real complexity behind a small interface, such as an effect with cleanup, a subscription, or a race-condition guard.
Exercise
A teammate writes useSlug(title), which returns title.toLowerCase().trim().replace(/\s+/g, '-') and calls no other hooks. Should it be a hook? Give a reason that involves where it can be called.
Show answer
No. It calls no hooks, so a plain function slugify(title) is enough. As a plain function it can also be called inside loops, .map() callbacks, and event handlers, where hooks are not allowed, and it can be unit tested without renderHook.