mediumRace ConditionsReact

The listener leak

A developer asked an AI assistant to track the window width in a React component for a responsive layout decision. The suggested code works initially, but after the component re-renders a few times, the resize handler starts firing multiple times per resize and the app slows down.

useWindowWidth.jsx
function useWindowWidth() {
  const [width, setWidth] = useState(window.innerWidth);

  useEffect(() => {
    window.addEventListener('resize', () => setWidth(window.innerWidth));
  });

  return width;
}

Why does the resize handler fire more and more times as the component re-renders?

window.addEventListener silently ignores duplicate listeners, so this can't actually be the cause.
useEffect only runs once by default, so extra listeners must come from React StrictMode alone.
The effect has no dependency array, so it re-runs after every render and adds a brand new listener each time without ever removing the old ones.
setWidth triggers a re-render loop that has nothing to do with the resize event itself.

Sign in with GitHub to submit an answer and track your progress.