Skip to content

.tip

ยท one of the small things

Every effect that subscribes returns an unsubscribe

An effect that adds a listener and returns no cleanup adds another one every time it re-runs, and the old ones keep firing against components that have unmounted.

useEffect(() => {
  const onResize = () => setWidth(window.innerWidth);
  window.addEventListener("resize", onResize);
  return () => window.removeEventListener("resize", onResize);
}, []);

In development, strict mode deliberately mounts, unmounts and remounts, so this bug shows up on the first render and not an hour in.

react