React · JavaScript · Frontend · TypeScript

React useEffect Mistakes: When You Don't Need an Effect and How to Fix the Rest

The useEffect mistakes I see most in React code reviews: derived state, effects that belong in event handlers, fetch race conditions, missing cleanup and stale closures.

Sander Yazıcıoğlu Published: 3 min read Türkçe oku

React useEffect Mistakes: When You Don't Need an Effect and How to Fix the Rest

When I review React code, the hook that produces the most bugs is useEffect. Not because it is broken, but because it is used as a general "do something when something changes" tool. On the dashboards I built at Testinium and on this site's own OS-style interface, removing effects fixed more bugs than adding them. Here are the patterns I flag most often, with the fix for each.

The rule of thumb

An effect is for synchronising with something outside React: a WebSocket, a browser API, a timer, a third-party widget, a network request. If the code only reads props and state and writes state, it almost certainly does not need an effect.

Mistake 1: storing derived state

// Before: two renders, and a moment where the values disagree
const [runs, setRuns] = useState<Run[]>([]);
const [failed, setFailed] = useState<Run[]>([]);
useEffect(() => {
  setFailed(runs.filter((r) => r.status === 'failed'));
}, [runs]);

The component first renders with the new runs and the old failed, then renders again. Compute it during render instead:

const failed = runs.filter((r) => r.status === 'failed');
// or, if the list is large and filtering is genuinely expensive:
const failedMemo = useMemo(() => runs.filter((r) => r.status === 'failed'), [runs]);

No sync, no extra render, no inconsistent frame.

Mistake 2: putting event logic in an effect

// Before
useEffect(() => {
  if (submitted) {
    api.save(form);
    toast('Saved');
  }
}, [submitted]);

This runs again whenever the component remounts with submitted still true, and in development Strict Mode it runs twice. The save happens because the user clicked, so it belongs in the click handler:

async function handleSubmit() {
  await api.save(form);
  toast('Saved');
}

Ask "why does this code run?" If the answer is "because the user did something", it is an event handler. If it is "because the component is on screen", it is an effect.

Mistake 3: resetting state when a prop changes

// Before
useEffect(() => { setDraft(''); }, [userId]);

Again a render with stale state, then a correction. Give the component a key and React resets all its state for you:

<CommentBox key={userId} userId={userId} />

Mistake 4: fetch race conditions

This one shows up in production as "the page sometimes shows the wrong project":

useEffect(() => {
  fetch(`/api/projects/${id}`).then((r) => r.json()).then(setProject);
}, [id]);

If the user switches from project A to B quickly and A's response arrives last, A wins. Cancel the stale request in cleanup:

useEffect(() => {
  const controller = new AbortController();
  fetch(`/api/projects/${id}`, { signal: controller.signal })
    .then((r) => r.json())
    .then(setProject)
    .catch((err) => {
      if (err.name !== 'AbortError') setError(err);
    });
  return () => controller.abort();
}, [id]);

For anything beyond a couple of calls, use a data-fetching library (TanStack Query, SWR, or your framework's loader). They handle caching, deduplication and races, and your components lose most of their effects.

Mistake 5: missing cleanup

Every subscription needs an unsubscribe. This is where React's development-mode double invoke helps: Strict Mode mounts, unmounts and mounts again, so a missing cleanup shows up as duplicate listeners right away.

useEffect(() => {
  const socket = new WebSocket(url);
  socket.onmessage = (e) => setEvents((prev) => [...prev, JSON.parse(e.data)]);
  return () => socket.close();
}, [url]);

For the server side of that connection, see realtime systems with Node.js and WebSocket.

For subscribing to an external store (a browser API like navigator.onLine, or a non-React store), useSyncExternalStore is safer than an effect plus state, because it avoids tearing during concurrent rendering:

const online = useSyncExternalStore(
  (cb) => {
    window.addEventListener('online', cb);
    window.addEventListener('offline', cb);
    return () => {
      window.removeEventListener('online', cb);
      window.removeEventListener('offline', cb);
    };
  },
  () => navigator.onLine,
);

Mistake 6: lying about dependencies

Silencing react-hooks/exhaustive-deps is the root of most stale-closure bugs: the effect keeps reading the value from the first render. If adding a dependency causes the effect to run too often, the fix is to change the code, not the array:

  • Use the updater form, setCount((c) => c + 1), so the effect doesn't need count.
  • Move a helper function inside the effect if only the effect uses it.
  • Move objects that never change outside the component, so they are not recreated each render.
// Before: interval recreated every second, or stale count if deps are faked
useEffect(() => {
  const t = setInterval(() => setCount(count + 1), 1000);
  return () => clearInterval(t);
}, [count]);

// After
useEffect(() => {
  const t = setInterval(() => setCount((c) => c + 1), 1000);
  return () => clearInterval(t);
}, []);

Treat the lint rule as an error in CI. If you are tightening types at the same time, TypeScript strict mode migration pairs well with it.

Why it matters for performance

Unneeded effects mean extra renders, and extra renders after user input hurt INP. On a heavy screen, removing a chain of "effect sets state, which triggers another effect" can be the difference between a sluggish and a snappy interaction. The Core Web Vitals post shows how to measure that.

Conclusion

Before writing useEffect, ask whether you are synchronising with something outside React. Compute derived values during render, put user-triggered logic in handlers, reset state with key, cancel stale fetches, always clean up, and never lie about dependencies. Most components get shorter and more correct at the same time.

All articles →