React · Middle · Question 53 of 75
Why does this chat effect reconnect when the theme changes?
useEffect(() => {
const conn = connect(roomId);
conn.on("connected", () => showToast("Connected", theme));
return () => conn.disconnect();
}, [roomId, theme]);- ✓Correct answer:
themeis read inside the effect, so it is a dependency; extract the non-reactive part intouseEffectEvent - 2Effects always re-run when any state changes
- 3
showToastmust be wrapped inuseMemo
Explanation
Every reactive value used in an effect must be listed. useEffectEvent lets the handler read the latest theme without making the effect depend on it.