ReactMedium

What is a dependency warning?

A dependency warning comes from the react-hooks/exhaustive-deps ESLint rule: "React Hook useEffect has a missing dependency: 'x'". It means the effect (or useMemo/useCallback) reads a reactive value that is not listed in its dependency array, which risks stale values. The fix is almost never to silence it, but to list the value or restructure the code.

What counts as a dependency

Props, state, context values, and anything computed from them during render, including functions and objects defined in the component body. Not needed: state setters, dispatch, refs, imported modules, values defined outside the component, and Effect Events from useEffectEvent.

How to resolve it

  1. Add the dependency if the effect should re-run when it changes.
  2. Move the value inside the effect if only the effect uses it (functions, option objects).
  3. Move it outside the component if it does not use props or state.
  4. Use an updater function to stop reading state: setItems((prev) => [...prev, item]).
  5. Use useEffectEvent (React 19.2) for logic that should read the latest values but should not cause the effect to re-run, such as logging or showing a notification with the current theme.
  6. Split the effect if it does two unrelated things.

Why not disable the rule

// eslint-disable-next-line react-hooks/exhaustive-deps hides real bugs (stale closures, missed updates) and stops the React Compiler from safely optimizing that code.

Setup

eslint-plugin-react-hooks v7 with the flat recommended config; it also includes React Compiler-powered rules.

Code example

tsx
1import { useEffect, useEffectEvent, useState } from "react";
2
3export function Notifications({ userId, soundOn }: { userId: string; soundOn: boolean }) {
4 const [items, setItems] = useState<string[]>([]);
5
6 // Warning version:
7 // useEffect(() => {
8 // const es = new EventSource(`/api/notify/${userId}`);
9 // es.onmessage = (e) => { setItems([...items, e.data]); if (soundOn) beep(); };
10 // return () => es.close();
11 // }, [userId]); // missing: items, soundOn
12
13 const onNotification = useEffectEvent((text: string) => {
14 if (soundOn) new Audio("/ding.mp3").play(); // reads latest soundOn, not a dependency
15 setItems((prev) => [...prev, text]); // updater: no need to read items
16 });
17
18 useEffect(() => {
19 const es = new EventSource(`/api/notify/${userId}`);
20 es.onmessage = (e) => onNotification(String(e.data));
21 return () => es.close();
22 }, [userId]); // complete: only reconnect when the user changes
23
24 return <ul>{items.map((t, i) => <li key={i}>{t}</li>)}</ul>;
25}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app