Sub topic 13
Native listeners with useEffect
This chapter assumes you know JSX props like onClick, the basics of useState, and how React runs effects after render. Most events need no more than a prop on a JSX element. This chapter covers the cases where that isn't enough.
When a prop does not fit
A prop such as onClick attaches a handler to an element you render. Some events come from objects you don't render:
window, forkeydown,resize, andonline/offlinedocument, for selection changes or clicks outside a component- Browser APIs, such as a
MediaQueryListor aWebSocket
There is no JSX element to put a prop on, so you register a native listener with addEventListener. Doing that during render would add a new listener on every render. Do it in useEffect, which runs after React commits the render, and remove the listener in the cleanup function.
The pattern
This modal closes when the user presses Escape:
import { useEffect } from 'react';
function Modal({ onClose }) {
useEffect(() => {
function handleKeyDown(e) {
if (e.key === 'Escape') {
onClose();
}
}
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [onClose]);
return <div role="dialog">...</div>;
}The effect has three parts:
- Setup. Define the handler and call
addEventListener. - Cleanup. Return a function that calls
removeEventListenerwith the same function reference. A new arrow function won't match, so the original listener would stay attached. - Dependencies. List every value the handler reads. Here that is
onClose.
The handler receives a native KeyboardEvent, not React's synthetic event. You still use e.key, but it is the browser's own object.
Updating state from a native listener
Native handlers can call state setters like any other function. Prefer a functional update or an empty dependency list when the handler doesn't need current values:
import { useEffect, useState } from 'react';
function WindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
function handleResize() {
setWidth(window.innerWidth);
}
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return <p>Window width: {width}px</p>;
}The handler reads window.innerWidth directly instead of a state variable, so it has no dependencies and the listener is added once.
Common errors
- Missing cleanup. Each mount adds another listener. In development, React Strict Mode mounts, unmounts, and remounts a component to expose this bug. You would see handlers firing twice.
- Stale values. If the handler reads state or props but the dependency array omits them, it keeps using the values from the render that created it. Add the dependency, or use a functional update such as
setCount(c => c + 1). - Unstable dependencies. If the parent passes a new
onClosefunction on every render, the effect removes and re-adds the listener each time. This is correct but wasteful. The parent can wrap the function inuseCallback. - Server rendering.
windowanddocumentdon't exist on the server. Effects run only in the browser, so access them inside the effect. AuseState(window.innerWidth)initializer, as in the example above, would fail during server rendering.
Choosing between a prop and an effect
| Situation | Use |
|---|---|
| Event on an element you render | JSX prop such as `onClick` |
| Event on `window` or `document` | `useEffect` with `addEventListener` |
| Event on a DOM node you reach with a ref | `useEffect` with the ref's `current` |
| Event stream outside the DOM, such as a socket | `useEffect` with subscribe and unsubscribe |
Exercise
A component adds a scroll listener to window inside useEffect but returns nothing from the effect. What goes wrong when the component unmounts, and how do you fix it?
Show answer
The listener stays attached after unmount, so it keeps running and may call state setters on a component that no longer exists. Each remount also adds another listener. Fix it by returning a cleanup function that calls window.removeEventListener('scroll', handleScroll) with the same handleScroll function that was added.