React · Middle · Question 55 of 75
How should a component subscribe to a browser event like resize?
useEffect(() => {
const onResize = () => setWidth(window.innerWidth);
window.addEventListener("resize", onResize);
return () => window.removeEventListener("resize", onResize);
}, []);- ✓Correct answer: Subscribe in
useEffectand unsubscribe with the same function in the cleanup - 2Subscribe directly in the component body
- 3Subscribe in
useMemo
Explanation
Without cleanup, each mount adds a listener that is never removed (Strict Mode makes this visible). For external stores, useSyncExternalStore is the more robust option.