7 useEffect Mistakes and What to Write Instead
Common useEffect mistakes in React: derived state, missing cleanup, race conditions in fetches, and effects for events. Each one with a simpler fix.
By UndieGravity, , 2 min read
useEffect is for synchronizing a component with something outside React: a network connection, a timer, a browser API. Most bugs come from using it for things that are not outside React at all. Here are the mistakes we see most in code reviews.
1. Storing derived state
// Avoid
const [fullName, setFullName] = useState("");
useEffect(() => setFullName(first + " " + last), [first, last]);
// Write
const fullName = first + " " + last;If a value can be calculated from props or state, calculate it during render. The effect version renders twice and can show stale values for a frame.
2. Handling user events in an effect
Sending a request because the user clicked Buy belongs in the click handler, not in an effect that watches a submitted flag. Effects run because something rendered; handlers run because the user did something.
3. Forgetting cleanup
useEffect(() => {
const id = setInterval(tick, 1000);
return () => clearInterval(id);
}, []);Every subscription, timer, or listener needs a cleanup function. In development, React runs effects twice on mount to surface missing cleanup.
4. Race conditions when fetching
useEffect(() => {
let ignore = false;
fetch(`/api/users/${id}`)
.then((res) => res.json())
.then((data) => {
if (!ignore) setUser(data);
});
return () => {
ignore = true;
};
}, [id]);Without the ignore flag, a slow response for an old id can overwrite the newer one. Better still: fetch in a Server Component, or use a data library such as TanStack Query that handles this for you.
5. Lying about dependencies
Leaving a value out of the dependency array to stop re-runs leads to stale data. If you need the latest value without re-running the effect, use useEffectEvent (React 19.2).
6. Resetting state when a prop changes
To reset a form when the user switches profiles, give the component a key: <ProfileForm key={userId} />. React creates a fresh instance, with no effect needed.
7. Chains of effects
Effect A sets state that triggers effect B, which sets state for effect C. Each step is another render. Compute the final values in one place, usually the event handler that started the change.
A useful test: if you removed the effect, would anything outside React be out of sync? If the answer is no, you probably do not need it.