React useEventListener Hook
React useEventListener hook for DOM event listeners. Automatic cleanup and TypeScript safety with JavaScript integration for Next.js apps.
Having trouble with event listener cleanup?
Join our Discord community for help from other developers.
Ever added event listeners in useEffect and forgot to clean them up? You know the drill—addEventListener in the effect, track the element ref, return a cleanup function with removeEventListener, handle all the edge cases when refs change. This free open source React useEventListener custom hook handles all that event management complexity so you can focus on your app logic instead of wrestling with cleanup and memory leaks in your React applications.
useEventListener showcase
Smart event handling with automatic cleanup:
This free open source React hook simplifies DOM event management with TypeScript support for modern JavaScript applications. Whether you're building keyboard shortcuts, scroll handlers, or interactive features in your Next.js projects, this React hook keeps your event listeners clean and reliable.
Installation
npx shadcn@latest add https://www.shadcn.io/registry/use-event-listener.json
npx shadcn@latest add https://www.shadcn.io/registry/use-event-listener.json
pnpm dlx shadcn@latest add https://www.shadcn.io/registry/use-event-listener.json
bunx shadcn@latest add https://www.shadcn.io/registry/use-event-listener.json
Why most event listener implementations suck
Look, you could manually add and remove event listeners in useEffect, track refs, handle cleanup, and deal with changing dependencies. But after debugging the third memory leak from forgotten removeEventListener calls, you'll appreciate having this handled properly.
Most developers forget to clean up event listeners when components unmount, causing memory leaks that accumulate over time in React applications. Or they add listeners in useEffect without proper cleanup, leading to duplicate listeners on re-renders. Some handle refs incorrectly and wonder why their events don't fire in TypeScript components.
The React hook automatically manages the entire event lifecycle—attach on mount, clean up on unmount, handle ref changes, and prevent stale handler issues in Next.js projects. No more memory leaks, no more lingering listeners.
Real talk—event listeners in React are trickier than they look in JavaScript development. Refs can be null, handlers can capture stale values, and cleanup is easy to mess up. This React hook gets all the edge cases right.
This free open source React hook handles the event listener boilerplate while you focus on building features. Whether you're creating React applications, Next.js projects, or TypeScript codebases, this custom hook keeps your event management bulletproof.
Features
- Versatile targets - Attach to window, document, DOM elements, or media query lists in React applications
- Automatic cleanup - Event listeners are removed on unmount or dependency changes in TypeScript components
- Type safety - Full TypeScript support with proper event type inference for Next.js projects
- Performance optimized - Handler function is stored in ref to prevent unnecessary re-renders in JavaScript development
- Multiple overloads - Different interfaces for different event targets in React frameworks
- Modern API - Uses standard addEventListener/removeEventListener in modern React applications
- Free open source - Designed for modern React development workflows
When you'll actually use this
Real talk—this isn't for every click handler in React applications. For simple component interactions, use onClick props. But when you need global listeners, document events, or complex ref-based listening, this React hook shines in Next.js projects.
Perfect for:
- Keyboard shortcuts - Global key handlers built with TypeScript for React development
- Scroll tracking - Window or element scroll monitoring using React patterns in JavaScript applications
- Outside click detection - Close dropdowns and modals on outside clicks in React components
- Resize handling - Responsive behavior for window size changes in Next.js applications
- Visibility tracking - Detect when elements enter/leave viewport using TypeScript validation
- Mouse interactions - Track mouse movements and gestures in React frameworks
- Touch events - Mobile touch and swipe gesture handling in JavaScript development
- Media query changes - Responsive breakpoint detection for TypeScript projects
API Reference
useEventListener
The hook automatically detects the target type and provides proper TypeScript support:
// Window events (no element provided)
useEventListener("scroll", (event) => console.log(event));
// Element events (with ref)
useEventListener("click", (event) => console.log(event), elementRef);
// With options
useEventListener("scroll", handler, undefined, { passive: true });
Parameters
Parameter | Type | Description |
---|---|---|
eventName | string | The event type to listen for |
handler | function | The event handler function |
element | RefObject | Optional element ref (defaults to window) |
options | object | Optional addEventListener options |
Common gotchas
Ref null states: The React hook waits for the ref to have a value before attaching listeners in TypeScript components. If your ref is always null, no listener gets attached in React applications.
Handler function ref storage: This prevents stale closures but means your handler always gets the latest values from your component's scope in Next.js projects. Usually what you want, but worth knowing for debugging.
Window fallback default behavior: When no element is provided, events attach to the window in JavaScript development. This is convenient for global listeners but can be surprising if you expect document events.
SSR safety handling: The React hook safely handles server-side rendering where window/document don't exist in TypeScript projects. Listeners only attach on the client side.
Performance event options: Use { passive: true }
for scroll and touch events to improve performance in React components. The hook passes options directly to addEventListener.
Memory leak prevention: Unlike manual addEventListener, this hook automatically cleans up all listeners on unmount, preventing accumulating event handlers in Next.js applications.
Related hooks you will also like
useClickAnyWhere
Global click detection built on useEventListener patterns
useOnClickOutside
Detect clicks outside specific elements with ref targeting
useHover
Track hover state with mouse enter and leave detection
useWindowSize
Track window size changes with resize event handling
useMediaQuery
Responsive design with CSS media query event detection
useEventCallback
Stable event callback references for optimal performance
Questions you might have
React useEventCallback Hook
React useEventCallback hook for stable event callbacks. Solve useCallback dependency issues with TypeScript support for Next.js applications.
React useHover Hook
React useHover hook for hover state detection. Track mouse interactions with precise event handling and TypeScript support for Next.js applications.