Course contentsShow
← React
Lesson 968 of 2,39625. Custom HooksFree lesson

Extracting Event Listener Logic

Build useEventListener to attach and clean up window or document event listeners in any component.

Extracting Event Listener Logic

You'll learn how to build a reusable useEventListener custom hook that handles attaching and cleaning up window or document event listeners in any component.

The Problem with Repeated Event Listener Code

You've likely written this pattern multiple times: attach an event listener in useEffect, then clean it up in the return function. When you need keyboard shortcuts, window resize handling, or scroll tracking across multiple components, you end up copying the same boilerplate everywhere.

Building useEventListener

A custom hook can encapsulate this entire pattern:

function useEventListener(eventName, handler, element = window) {
  useEffect(() => {
    // Ensure the element supports addEventListener
    const isSupported = element && element.addEventListener;
    if (!isSupported) return;

    // Attach the event listener
    element.addEventListener(eventName, handler);

    // Clean up on unmount or when dependencies change
    return () => {
      element.removeEventListener(eventName, handler);
    };
  }, [eventName, handler, element]);
}

Using Your Hook

Now any component can listen to events without repeating cleanup logic:

function App() {
  const [key, setKey] = useState('');

  useEventListener('keydown', (e) => setKey(e.key));

  return <div>Last key pressed: {key}</div>;
}

The hook handles both attaching the listener and removing it when the component unmounts or dependencies change.

Why This Works

Think of useEventListener as a "subscription manager" — you tell it what to listen for and what to do, and it handles all the messy setup and teardown automatically. You can reuse it for window resizes, document clicks, keyboard events, or any DOM event across your entire application.

Key Takeaway: Extract event listener patterns into a useEventListener hook to eliminate repetitive setup/cleanup code and make event handling consistent across your app.