Sub topic 6
Event listeners, subscriptions and timers
This chapter assumes you know useState, closures, and how useEffect uses a dependency array and a cleanup function. Event listeners, subscriptions and timers all start something that keeps running after the effect body finishes. That makes them the most common reason to write cleanup.
The pattern: start, then stop
Each of these resources follows the same pattern. The effect starts it, and the cleanup function stops it. React runs the cleanup before the next run of the effect and when the component unmounts.
| Resource | Start | Stop |
|---|---|---|
| Event listener | `addEventListener` | `removeEventListener` |
| Timer | `setInterval` or `setTimeout` | `clearInterval` or `clearTimeout` |
| Subscription | `subscribe(callback)` | the unsubscribe function |
Without cleanup, each run adds another listener or timer. The old ones keep calling setState on a component that may no longer exist.
Event listeners
This hook tracks the window width. The listener is added once, and the cleanup removes it.
import { useEffect, useState } from 'react';
function useWindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
function handleResize() {
setWidth(window.innerWidth);
}
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return width;
}removeEventListener only works if you pass the same function reference that you added. That is why handleResize is declared as a named function inside the effect instead of being written inline twice.
Timers and stale values
A timer callback is a closure. It keeps the values from the render in which the effect ran. If the effect has an empty dependency array, a callback that reads seconds would see 0 forever. The functional update form avoids this because React passes the current value to your function.
import { useEffect, useState } from 'react';
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const id = setInterval(() => {
setSeconds((s) => s + 1);
}, 1000);
return () => clearInterval(id);
}, []);
return <p>{seconds} seconds elapsed</p>;
}The interval is created once. Each tick calls setSeconds with a function, so the effect never needs to read seconds and does not list it as a dependency.
How the lifecycle runs
The diagram shows what happens when a dependency changes while a timer is running.
Subscriptions
Other subscriptions work the same way. For example, a WebSocket or a store may return an unsubscribe function, or have a close method. Return a cleanup function that calls it.
import { useEffect, useState } from 'react';
function useOnlineStatus() {
const [online, setOnline] = useState(navigator.onLine);
useEffect(() => {
const update = () => setOnline(navigator.onLine);
window.addEventListener('online', update);
window.addEventListener('offline', update);
return () => {
window.removeEventListener('online', update);
window.removeEventListener('offline', update);
};
}, []);
return online;
}Common errors
- Forgetting the cleanup, so listeners and timers pile up with every re-run.
- Passing a different function to
removeEventListenerthan toaddEventListener. - Reading state inside a timer with an empty dependency array and getting an old value.
- Starting a listener in an event handler instead of an effect, with no component lifecycle to stop it.
Exercise
A component sets up setInterval(() => console.log(count), 1000) in an effect with [] as dependencies. The count increases, but the console always prints 0. Why does this happen, and what are two ways to fix it?
Show answer
The interval callback closes over count from the first render, where it was 0, and the effect never re-runs. One fix is to add count to the dependency array so the cleanup clears the old interval and a new one starts with the current value. The other is to keep the empty array and avoid reading count in the callback, which works only when you are updating state, for example setCount((c) => c + 1).