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);
}, []);

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.

Further reading

Problem with a question

React · Middle · question 55

Test yourself

Take the React · Middle quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz