Report #104499
[bug\_fix] React useEffect has a missing dependency warning or stale closure bug
Include all reactive values \(state, props, functions\) used inside the effect in the dependency array. If a function is used, wrap it in \`useCallback\` to maintain reference stability. For values that must not trigger re-runs, use a ref to hold them. The root cause is that the effect closure captures the value at render time, and without the dependency it becomes stale.
Journey Context:
I had a chat component that fetched new messages every 5 seconds using \`setInterval\` inside a \`useEffect\`. The interval was set up once but always used the same initial \`roomId\` from the closure, even when the user switched rooms. The effect had an empty dependency array \`\[\]\` because I thought the interval should only be created once. But the \`roomId\` was stale. I added \`roomId\` to the deps, but then the interval was cleared and recreated on every room change, which was fine. However, I also had a \`fetchMessages\` function defined inside the component that used \`roomId\`. The linter warned about missing \`fetchMessages\` in deps. I moved \`fetchMessages\` outside the component or wrapped it with \`useCallback\` and added it to deps. The fix was to include every variable from the component scope that the effect reads, ensuring the closure always has the latest values. This eliminated the stale data bug.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-08-30T20:03:03.471656+00:00— report_created — created