Sub topic 6
Event Listeners, Subscriptions and Timers
This chapter covers the most common job for an effect: connecting a component to something that keeps running outside React. It assumes you know useState, closures, and the basic useEffect syntax and dependency array from earlier chapters. It also assumes you know that an effect can return a cleanup function.
Why these cases need cleanup
Event listeners, subscriptions and timers have one thing in common. Each one starts something that lives until you stop it. A DOM listener keeps firing, a WebSocket stays open, and an interval keeps ticking, even after the component that created it is gone.
If the effect only starts the thing, every mount and every dependency change adds another copy. You get duplicate handlers, calls to setState on components that no longer exist, and memory that is never released.
The rule is that every effect that starts a long-lived thing returns a function that stops it.
| Resource | Start | Stop |
|---|---|---|
| DOM event listener | `addEventListener` | `removeEventListener` |
| Interval | `setInterval` | `clearInterval` |
| Timeout | `setTimeout` | `clearTimeout` |
| WebSocket or `EventSource` | `new WebSocket(url)` | `socket.close()` |
| Observer (resize, intersection) | `observer.observe(el)` | `observer.disconnect()` |
| Store or emitter subscription | `store.subscribe(fn)` | the function `subscribe` returned |
Event listeners
Browser events that fire outside React's control, such as resize, online, keydown on window, or scroll on document, need an effect. This custom hook tracks the window width:
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;
}The empty dependency array means the effect runs once after mount. The cleanup runs once on unmount. The handler uses only setWidth, which React guarantees is stable, so nothing is missing from the array.
Edge cases with listeners
- Same function reference.
removeEventListeneronly works with the exact function passed toaddEventListener. Define the handler inside the effect and use that same variable in both calls. Writing a second inline arrow function in the cleanup silently removes nothing. - Matching options. The
captureoption must match between add and remove. If you add with{ capture: true }, remove with{ capture: true }. Options such aspassiveandoncedo not affect removal. - Server rendering.
useState(window.innerWidth)throws when the component renders on a server, becausewindowdoes not exist there. If your app does server rendering, start with a fixed value and read the real width inside the effect. - Elements React owns. If you attach a listener to an element through a ref, do it in the effect and remove it in the cleanup. For ordinary clicks on your own JSX, use
onClickinstead. Reserve effects for targets React does not manage.
Timers
An interval is a subscription to the clock. This component counts seconds:
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 functional update (s) => s + 1 is what lets the dependency array stay empty. If you wrote setSeconds(seconds + 1), the callback would close over the seconds value from the first render, which is 0. The interval would set the state to 1 every second and the display would stop at 1. This is a stale closure, and a later chapter treats it in full.
You have two valid fixes:
- Use a functional update so the effect never reads
seconds, and keep[]. - Add
secondsto the array. The effect then tears down and recreates the interval every second. That works, but it resets the timing each tick and does more work than needed.
Timeouts and debouncing
A timeout works the same way, and its cleanup cancels a call that has not fired yet. That makes a debounce short to write:
import { useEffect, useState } from 'react';
function SearchBox({ onSearch }) {
const [text, setText] = useState('');
useEffect(() => {
const id = setTimeout(() => onSearch(text), 400);
return () => clearTimeout(id);
}, [text, onSearch]);
return (
<input value={text} onChange={(e) => setText(e.target.value)} />
);
}Each keystroke changes text. React runs the previous cleanup, which cancels the pending timeout, and then starts a new 400 ms wait. onSearch only runs after the user pauses. Note that onSearch is a dependency. If the parent passes a new inline function on every render, the timer restarts on every parent render, and the debounce may never fire. Wrap the callback in useCallback in the parent, or see the chapters on unstable dependencies and reading the latest values.
Subscriptions
A subscription is any source that pushes data to you over time: WebSockets, server-sent events, a chat SDK, or a store with a subscribe method. The shape is always the same. Connect, register a handler, and return a function that disconnects.
import { useEffect, useState } from 'react';
function LiveFeed({ channel }) {
const [messages, setMessages] = useState([]);
useEffect(() => {
setMessages([]);
const socket = new WebSocket(`wss://example.com/feed/${channel}`);
socket.addEventListener('message', (event) => {
setMessages((prev) => [...prev, event.data]);
});
return () => socket.close();
}, [channel]);
return (
<ul>
{messages.map((m, i) => (
<li key={i}>{m}</li>
))}
</ul>
);
}When channel changes, React runs the old cleanup first, which closes the old socket. Then it runs the effect again with the new channel. The component is always connected to exactly one channel, and the effect describes how to stay in sync with the channel prop.
The socket variable lives inside the effect. Keep it there. Storing the connection in state or a module variable invites bugs where cleanup closes the wrong one.
When to prefer `useSyncExternalStore`
If the subscription feeds a value that you only read, such as navigator.onLine, a media query, or a store like Redux, React provides useSyncExternalStore. It avoids the tearing problem, where different parts of the UI show different values during a concurrent render. Library authors and custom hooks over external stores should reach for it first. For one-off connections that you open and close, such as a socket tied to a prop, an effect is the right tool.
The lifecycle in order
The order of calls matters when dependencies change. React always cleans up the previous run before starting the next one, and the cleanup sees the values from the render that created it.
Strict Mode and these effects
In development, Strict Mode mounts a component, runs the cleanup, and mounts it again. For a correct effect this is invisible. The listener is added, removed and added again, so one listener remains.
If you see two sockets open, two ticking intervals, or duplicate event handling in development, the cleanup is missing or incomplete. Strict Mode is exposing a real bug. It would also show up in production when the dependencies change or the component remounts.
Common mistakes
- Starting a timer or listener and returning nothing.
- Removing a listener with a different function reference than the one added.
- Reading state inside a long-lived callback while leaving that state out of the dependency array.
- Calling
clearIntervalwith anidfrom outside the effect, where it may refer to an older run. - Opening the connection in an event handler instead of an effect, so it is not tied to the component's lifetime.
Exercise
This hook is meant to log key presses on the whole page. Name two bugs. function useKeyLogger() { useEffect(() => { window.addEventListener('keydown', (e) => console.log(e.key)); return () => window.removeEventListener('keydown', (e) => console.log(e.key)); }, []); }
Show answer
The cleanup passes a new arrow function, not the one that was added, so the listener is never removed. Every mount, including the second mount in Strict Mode, adds another listener and logs each key more than once. The fix is to define function handleKeyDown(e) { console.log(e.key); } inside the effect and pass handleKeyDown to both addEventListener and removeEventListener. The second bug is that the code is only a bug in effect if the keydown handler ever needs props or state, because it would then capture stale values. Here it uses neither, so the one real bug is the mismatched reference.
Exercise
A countdown component starts at start seconds. The effect uses setInterval(() => setLeft(left - 1), 1000) with [] as dependencies. The display jumps from start to start - 1 and stays there. Explain why and give the smallest fix.
Show answer
The interval callback closes over left from the first render, so it always computes start - 1. The smallest fix is the functional update, setLeft((l) => l - 1), which does not read left from the closure. The array can stay empty. Add a stop condition separately if the countdown should end at zero.