Sub topic 13
Native listeners with useEffect
Most of the time you attach events with props such as onClick and onChange. This chapter covers the cases where those props do not reach the event you need. It shows how to register a native browser listener from a component, how to remove it, and what goes wrong when you skip a step.
It assumes you know useState, the basics of useEffect (the effect function, the cleanup function, and the dependency array), and how React passes handlers as props.
When a prop is not enough
A JSX prop can only attach a handler to an element that your component renders. Some events have no such element, or need options that React props cannot set.
- Events on
windowordocument, such askeydown,resize,online, andscrollon the page. - Events on a
MediaQueryList,WebSocket,IntersectionObserver, or another browser object that is not in your JSX. - Listener options such as
{ passive: false }. React registerswheel,touchstart, andtouchmoveas passive at its root, sopreventDefault()in anonWheelprop has no effect. - Events that a third-party library emits on a DOM node it controls.
For everything else, keep using props. They are cleaned up for you, and they follow the component's lifecycle.
The basic pattern
A native listener is a side effect: it connects your component to something outside React. Register it in useEffect and remove it in the cleanup function.
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>;
}React runs the effect after the component appears on screen. When the component unmounts, or when a dependency changes, React runs the cleanup first. The next effect then adds a fresh listener.
Cleanup rules
removeEventListener only removes a listener if it receives the same event type, the same function reference, and the same capture flag as addEventListener.
- Define the handler inside the effect, so the function you add is the function you remove.
- Do not pass a fresh arrow function to both calls. Two separate arrow functions are two different references, and the removal does nothing.
- If you add with
{ capture: true }, remove with{ capture: true }.
React Strict Mode in development runs every effect twice on mount (setup, cleanup, setup). If your cleanup is correct, this is invisible. If you see duplicated behavior only in development, a missing cleanup is the likely cause.
Updating state from a native listener
State updates work the same way as in a React handler. Use the setter, and prefer a functional update when the new value depends on the old one. A native listener created once captures the state values from the render that created it, so reading count directly inside it gives you a stale value.
import { useEffect, useState } from 'react';
function WindowWidth() {
const [width, setWidth] = useState(0);
useEffect(() => {
function handleResize() {
setWidth(window.innerWidth);
}
handleResize();
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return <p>Window width: {width}px</p>;
}The empty dependency array is correct here. The handler uses only the setter, which React keeps stable, and a browser global. Reading window inside the effect, not during render, also keeps the component safe for server rendering, where window does not exist.
React 18 batches updates from native listeners, timeouts, and promises, just as it does for React handlers. Several set calls in one listener cause one re-render.
The stale closure problem
The first example lists onClose in its dependency array. That is correct, because the effect reads onClose. It has a cost: if the parent passes a new function on every render, the effect removes and re-adds the listener on every render.
// Parent: creates a new function each render
<Modal onClose={() => setOpen(false)} />This works, but it does needless work. Leaving onClose out of the array is the wrong fix, because the listener would then call an old version of the function that may read old state.
A common solution keeps the latest handler in a ref and subscribes once.
import { useEffect, useRef } from 'react';
function useWindowEvent(type, handler) {
const handlerRef = useRef(handler);
useEffect(() => {
handlerRef.current = handler;
});
useEffect(() => {
function listener(e) {
handlerRef.current(e);
}
window.addEventListener(type, listener);
return () => window.removeEventListener(type, listener);
}, [type]);
}
function Modal({ onClose }) {
useWindowEvent('keydown', e => {
if (e.key === 'Escape') {
onClose();
}
});
return <div role="dialog">...</div>;
}The first effect has no dependency array, so it runs after every render and copies the newest handler into the ref. The second effect subscribes once per event type. The registered listener reads handlerRef.current when the event fires, so it always calls the newest handler.
Listening on an element you render
When you need listener options on an element in your own JSX, get the node with a ref and attach the listener in the effect. The ref is set by the time effects run.
import { useEffect, useRef, useState } from 'react';
function ZoomArea() {
const areaRef = useRef(null);
const [zoom, setZoom] = useState(1);
useEffect(() => {
const el = areaRef.current;
function handleWheel(e) {
e.preventDefault();
setZoom(z => Math.min(3, Math.max(0.5, z - e.deltaY / 500)));
}
el.addEventListener('wheel', handleWheel, { passive: false });
return () => el.removeEventListener('wheel', handleWheel);
}, []);
return (
<div ref={areaRef} style={{ height: 200, overflow: 'hidden' }}>
<div style={{ transform: `scale(${zoom})` }}>Scroll to zoom</div>
</div>
);
}{ passive: false } tells the browser that the listener may call preventDefault(). Here that stops the page from scrolling while the user zooms. Copy areaRef.current into a local variable, as el does here, so the cleanup removes the listener from the same node that received it.
How native listeners interact with React handlers
Since React 17, React attaches its own listeners to the root container where you call createRoot, not to each element. A native event therefore reaches your code in this order.
- Native listeners on the target element, then on its ancestors inside the root.
- React's listener on the root, which runs your
onClick-style props. - Native listeners on elements above the root, such as
documentandwindow.
Two consequences follow.
- A native listener on a child element runs before the React handler. If it calls
stopPropagation(), the event never reaches the root, and the React handler does not run. - A React handler that calls
e.stopPropagation()also stops the native event at the root. Native listeners ondocumentandwindowwill not see it. This is a common reason for an "outside click" listener ondocumentthat seems to miss clicks.
Choosing between a prop and a native listener
| Situation | Use | Reason |
|---|---|---|
| Click, change, or key event on an element you render | JSX prop | Automatic cleanup, works with React's event system |
| Key or resize event on `window` or `document` | `useEffect` listener | No JSX element exists to attach to |
| `preventDefault()` on `wheel` or touch events | `useEffect` with a ref | React registers these as passive |
| Event from a third-party widget or browser API | `useEffect` listener | The source is outside React |
| Need to run before every other handler | `useEffect` with `capture: true` | Capture runs first |
Common mistakes
- Forgetting the cleanup function, or returning nothing from the effect.
- Passing different function references to
addEventListenerandremoveEventListener. - Omitting a value the handler reads from the dependency array, which causes stale values.
- Reading
windowordocumentduring render, which fails on the server. - Using a native listener where a prop would do. This makes the code longer and loses automatic cleanup.
Exercise
A component adds window.addEventListener('scroll', () => setY(window.scrollY)) inside useEffect(..., []) and returns () => window.removeEventListener('scroll', () => setY(window.scrollY)). Every time the component unmounts and remounts, scroll updates fire more often. What is wrong, and how do you fix it?
Show answer
The cleanup passes a new arrow function, which is a different reference from the one that was added, so removeEventListener removes nothing and each mount leaks a listener. Declare function handleScroll() { setY(window.scrollY); } inside the effect, pass handleScroll to both addEventListener and removeEventListener, and return the removal from the cleanup.
Exercise
You add a mousedown listener on document to close a dropdown when the user clicks outside it. Clicks on a button whose React onClick calls e.stopPropagation() never close the dropdown. Why does this happen, and what option on the listener avoids it?
Show answer
React's stopPropagation() also calls it on the native event at the React root, so the event never bubbles up to document. Registering the document listener with { capture: true } (and removing it with the same option) makes it run during the capture phase, before the event reaches the button's handler, so it cannot be stopped.