- Published on
Event Management and Cleanup in React
- Authors

- Name
- Mamun Rashid
Effective Event Management and Cleanup in React: A Complete Guide
Handling events efficiently matters if you want a React UI that stays interactive as it grows. React's declarative nature makes clicks, typing and scrolling easy to respond to. Listeners you manage yourself are another story. Once direct DOM access or a third-party library is involved, they need careful handling, or you end up with memory leaks and a slow page.
This post covers why event management matters in React and how to add listeners at runtime and clean them up properly. We'll go through the core principles with React examples and build a reusable pattern you can use for events in any component.
Why Is Event Management and Cleanup Important in React?
Most of the time we handle events declaratively, with handlers tied directly to elements (onClick, onChange). Some cases make us manage listeners by hand instead: the global window object, a third-party library, or direct DOM access. If we get that wrong, listeners we no longer use stay active, and that causes trouble:
- Memory leaks. A listener attached by a component can stick around after the component unmounts and keep using memory nobody needs.
- Slower pages. Piles of unneeded listeners can slow an app down, more so on complex or interactive pages.
- Odd behavior. An event that fires for a component that has already unmounted can throw errors or do something the user didn't expect.
Removing each listener once it's no longer needed avoids all three.
Core Principles of Event Management in React
When we handle events outside React's declarative approach, for example by attaching listeners to the window or document, a few principles apply:
- Register listeners on mount. Attach them when the component mounts, or when some condition calls for them.
- Clean up on unmount. Remove them when the component unmounts or when you no longer need them, so they don't leak memory.
- Keep side effects out of rendering. Event management logic stays separate from the component's render, which avoids unnecessary re-renders.
Hook to the Rescue: useEffect
Setting up and tearing down listeners is lifecycle work, and in React that goes in the useEffect hook. useEffect runs side effects, like attaching a listener, after the component renders. It can also return a cleanup function, which is where we remove those listeners when the component unmounts.
A Reusable Event Management Hook in React
Window resizing, scroll events and keyboard input all follow the same pattern, so we can wrap it in a custom React hook. The hook registers the listener, cleans it up and keeps the whole thing cheap.
Example: A useEventListener Hook
import { useEffect, useRef } from 'react';
function useEventListener(eventType, callback, element = window) {
const savedCallback = useRef(callback);
// Update ref when callback changes (avoids stale closures)
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
// Set up the event listener
useEffect(() => {
// Check if element supports addEventListener
const targetElement = element?.current ?? element;
if (!targetElement?.addEventListener) return;
// Create a handler that calls the stored callback
const eventHandler = (event) => savedCallback.current(event);
// Add event listener
targetElement.addEventListener(eventType, eventHandler);
// Clean up the event listener on component unmount
return () => {
targetElement.removeEventListener(eventType, eventHandler);
};
}, [eventType, element]);
}
export default useEventListener;
TypeScript Version
import { useEffect, useRef, RefObject } from 'react';
type EventMap<T> = T extends Window
? WindowEventMap
: T extends Document
? DocumentEventMap
: T extends HTMLElement
? HTMLElementEventMap
: never;
function useEventListener<T extends Window | Document | HTMLElement, K extends keyof EventMap<T>>(
eventType: K,
callback: (event: EventMap<T>[K]) => void,
element?: T | RefObject<T> | null,
): void {
const savedCallback = useRef(callback);
// Update ref when callback changes
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
useEffect(() => {
// Default to window if no element provided
const targetElement =
(element && 'current' in element ? element.current : element) ?? window;
if (!targetElement?.addEventListener) return;
const eventHandler = (event: Event) => savedCallback.current(event as EventMap<T>[K]);
targetElement.addEventListener(eventType as string, eventHandler);
return () => {
targetElement.removeEventListener(eventType as string, eventHandler);
};
}, [eventType, element]);
}
export default useEventListener;
How Does This Hook Work?
- The callback lives in a ref.
useRefstores it, so the hook always calls the latest version without extra re-renders or stale closures. - It accepts an element directly or a React ref (
element?.current). - It registers the listener for the given event type (
eventType) on the element you pass in (elementfalls back towindowif you pass nothing). - It cleans up after itself. When the component using the hook unmounts, or the event type or element changes, the listener comes off so it can't leak memory.
- The TypeScript version infers proper types for event names and callbacks.
Using useEventListener in a React Component
Here is the hook in a real component. Say we want to handle the resize event on the window object and adjust the layout as the size changes.
import React, { useState, useEffect } from 'react';
import useEventListener from './useEventListener';
function ResizeComponent() {
// Initialize with undefined to handle SSR
const [windowSize, setWindowSize] = useState({
width: undefined,
height: undefined,
});
// Set initial size on mount
useEffect(() => {
setWindowSize({
width: window.innerWidth,
height: window.innerHeight,
});
}, []);
const handleResize = () => {
setWindowSize({
width: window.innerWidth,
height: window.innerHeight,
});
};
// Use the custom hook to handle the resize event
useEventListener('resize', handleResize);
return (
<div>
<h2>Window Size:</h2>
{windowSize.width ? (
<p>{`Width: ${windowSize.width}px, Height: ${windowSize.height}px`}</p>
) : (
<p>Measuring...</p>
)}
</div>
);
}
export default ResizeComponent;
Using with Element Refs
The same hook can attach a listener to a specific DOM element through a ref:
import React, { useRef } from 'react';
import useEventListener from './useEventListener';
function ClickableDiv() {
const divRef = useRef(null);
const handleClick = (event) => {
console.log('Div clicked!', event.target);
};
// Attach listener to specific element
useEventListener('click', handleClick, divRef);
return (
<div ref={divRef} style={{ padding: '20px', border: '1px solid black' }}>
Click me!
</div>
);
}
export default ClickableDiv;
Key Points:
The
useEventListenerhook attaches aresizelistener to thewindow.State starts as
undefinedso that server-side rendering (SSR) is handled safely.Each time the window resizes, the component puts the new dimensions in state.
The hook works with global objects (
window,document) as well as element refs.The listener is removed automatically when the component unmounts.
Cleaner syntax (no manual
removeEventListener)Can abort multiple listeners with one controller
Better for handling request cancellation alongside event cleanup
Part of the web platform standard
Event Management in Complex Scenarios
Simple events like click or resize are easy. Some situations ask more of your event management:
Several event types at once. Sometimes we need both
keydownandkeyup, for example. We can extend ouruseEventListenerhook to take more than one event type.Third-party libraries. A library may emit custom events that we have to listen for. With proper cleanup, removing the component that uses the library doesn't leave orphaned listeners behind.
Global listeners. Anything attached to
windowordocumentneeds extra attention. Forget to remove one of these and it can hurt performance across the whole app.
Example: Handling Multiple Event Types
Here's the custom hook extended to handle several event types:
import { useEffect, useRef } from 'react';
function useMultiEventListener(events, callback, element = window) {
const savedCallback = useRef(callback);
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
useEffect(() => {
const targetElement = element?.current ?? element;
if (!targetElement?.addEventListener) return;
const eventHandler = (event) => savedCallback.current(event);
// Register all event types
events.forEach((eventType) => targetElement.addEventListener(eventType, eventHandler));
// Clean up all event listeners
return () => {
events.forEach((eventType) =>
targetElement.removeEventListener(eventType, eventHandler),
);
};
}, [events, element]); // Note: 'events' array should be stable (use useMemo if needed)
}
export default useMultiEventListener;
Example Usage:
function MultiEventComponent() {
const handleKeyEvents = (event) => {
console.log(`Key event: ${event.type}, Key: ${event.key}`);
};
useMultiEventListener(['keydown', 'keyup'], handleKeyEvents);
return (
<div>
<h2>Press any key and check the console!</h2>
</div>
);
}
Here useMultiEventListener listens for both keydown and keyup. Any component that needs several events can reuse it the same way.
Best Practices for Event Management in React
Habits worth keeping when you manage events in React:
- Always clean up. Whether we use
useEffector a custom hook, every listener has to come off when the component unmounts. - Keep callbacks in refs. That avoids stale closures, and the effect doesn't re-run every time the callback function changes.
- Touch the DOM directly as little as possible. Use React's declarative event system (
onClick,onChangeand so on) wherever it fits, and save direct DOM listeners for special cases likewindowevents,documentevents or a third-party library. - Put event logic in custom hooks. A hook like
useEventListenerpulls that logic out of your components, so they're easier to read and reuse. - Think about SSR. Before using browser APIs like
windowordocument, check that they exist, and initialize state so server rendering doesn't throw. - Try newer APIs. Where browser support allows,
AbortControllermakes cleanup simpler. - Test your listeners and their cleanup, especially in complex components with several listeners.
Conclusion
A React app that stays fast and maintainable needs its events managed well. When hooks add listeners and clean them up again, we prevent memory leaks and the app performs better.
What we covered:
- A reusable
useEventListenerhook that adds and removes listeners as components need them. - Harder cases, like multiple events or global listeners, handled with proper cleanup.
- The habits that keep event handling efficient.
The same patterns work in large, complex React apps, and they don't cost you performance or maintainability.
Enjoyed this post?
Subscribe to get notified about new posts and updates. No spam, unsubscribe anytime.
By subscribing, you agree to our Privacy Policy. You can unsubscribe at any time.
Discussion
Loading comments...
This website is still under development. If you encounter any issues, please contact me.
Found this useful? Support the blog