Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 | 61x 83x 21x 62x 1x 61x 3x 58x 91x 91x 91x 91x 89x 89x 6x 83x 83x 2x 81x 56x 81x 81x 4x 81x 81x 81x | import { useEffect, useRef } from "react";
/**
* Options for useEventListener hook
*/
export interface UseEventListenerOptions {
/**
* Whether the event listener is enabled
* @default true
*/
enabled?: boolean;
/**
* Whether to use event capture phase
* @default false
*/
capture?: boolean;
/**
* Whether to use passive event listener for performance optimization
* Useful for scroll/touch events
* @default undefined (browser default)
*/
passive?: boolean;
/**
* Whether the handler should be invoked only once and then removed
* @default false
*/
once?: boolean;
}
/**
* Supported event target types
*/
export type EventTargetType<T extends HTMLElement = HTMLElement> =
| Window
| Document
| HTMLElement
| React.RefObject<T | null>
| null
| undefined;
/**
* Check if target is a RefObject
*/
function isRefObject<T extends HTMLElement>(
target: EventTargetType<T>
): target is React.RefObject<T | null> {
return (
target !== null &&
target !== undefined &&
typeof target === "object" &&
"current" in target
);
}
/**
* Extract actual DOM element from target
*/
function getTargetElement<T extends HTMLElement>(
target: EventTargetType<T>
): Window | Document | HTMLElement | null {
// Default to window if target is undefined (not provided)
if (target === undefined) {
return typeof window !== "undefined" ? window : null;
}
// If null is passed, return null (no listener)
if (target === null) {
return null;
}
// Extract element from RefObject
if (isRefObject(target)) {
return target.current;
}
return target;
}
// Overload 1: Window events (default when element is omitted or Window)
/**
* Adds an event listener to the window (default) or specified element.
*
* @param eventName - The event type to listen for
* @param handler - The callback function called when the event fires
* @param element - The target element (defaults to window)
* @param options - Configuration options
*
* @example
* ```tsx
* // Window resize event
* useEventListener("resize", (e) => {
* console.log("Window resized:", window.innerWidth);
* });
* ```
*/
export function useEventListener<K extends keyof WindowEventMap>(
eventName: K,
handler: (event: WindowEventMap[K]) => void,
element?: Window | null,
options?: UseEventListenerOptions
): void;
// Overload 2: Document events
/**
* Adds an event listener to the document.
*
* @example
* ```tsx
* // Document keydown event
* useEventListener("keydown", (e) => {
* console.log("Key pressed:", e.key);
* }, document);
* ```
*/
export function useEventListener<K extends keyof DocumentEventMap>(
eventName: K,
handler: (event: DocumentEventMap[K]) => void,
element: Document,
options?: UseEventListenerOptions
): void;
// Overload 3: HTMLElement events
/**
* Adds an event listener to an HTMLElement.
*
* @example
* ```tsx
* // HTMLElement click event
* const button = document.getElementById("myButton");
* useEventListener("click", (e) => {
* console.log("Button clicked");
* }, button);
* ```
*/
export function useEventListener<K extends keyof HTMLElementEventMap>(
eventName: K,
handler: (event: HTMLElementEventMap[K]) => void,
element: HTMLElement | null,
options?: UseEventListenerOptions
): void;
// Overload 4: RefObject<HTMLElement>
/**
* Adds an event listener to an element referenced by a RefObject.
*
* @example
* ```tsx
* // RefObject event
* const ref = useRef<HTMLDivElement>(null);
* useEventListener("scroll", (e) => {
* console.log("Element scrolled");
* }, ref);
* ```
*/
export function useEventListener<
K extends keyof HTMLElementEventMap,
T extends HTMLElement
>(
eventName: K,
handler: (event: HTMLElementEventMap[K]) => void,
element: React.RefObject<T | null>,
options?: UseEventListenerOptions
): void;
// Overload 5: Custom events (fallback for non-standard events)
/**
* Adds an event listener for custom events.
*
* @example
* ```tsx
* // Custom event
* useEventListener("myCustomEvent", (e) => {
* console.log("Custom event fired");
* }, document);
* ```
*/
export function useEventListener(
eventName: string,
handler: (event: Event) => void,
element?: EventTargetType,
options?: UseEventListenerOptions
): void;
/**
* A React hook for adding event listeners to DOM elements with automatic cleanup.
* Supports window, document, HTMLElement, and RefObject targets.
*
* Features:
* - Type-safe event handling with TypeScript inference
* - Automatic cleanup on unmount
* - Handler stability (no re-registration on handler change)
* - SSR compatible
*
* @param eventName - The event type to listen for
* @param handler - The callback function called when the event fires
* @param element - The target element (defaults to window)
* @param options - Configuration options
*
* @example
* ```tsx
* // Window resize event (default target)
* useEventListener("resize", (e) => {
* console.log("Window resized:", window.innerWidth);
* });
*
* // Document keydown event
* useEventListener("keydown", (e) => {
* if (e.key === "Escape") closeModal();
* }, document);
*
* // Element click event with ref
* const buttonRef = useRef<HTMLButtonElement>(null);
* useEventListener("click", handleClick, buttonRef);
*
* // With options
* useEventListener("scroll", handleScroll, window, {
* passive: true,
* capture: false,
* });
*
* // Conditional activation
* useEventListener("mousemove", handleMouseMove, document, {
* enabled: isTracking,
* });
* ```
*/
export function useEventListener(
eventName: string,
handler: (event: Event) => void,
element?: EventTargetType,
options: UseEventListenerOptions = {}
): void {
const { enabled = true, capture = false, passive, once = false } = options;
// Store handler in ref to avoid re-registering event listeners
const handlerRef = useRef(handler);
// Update handler ref on each render to always call the latest handler
handlerRef.current = handler;
useEffect(() => {
// SSR check
Iif (typeof window === "undefined") {
return;
}
// Don't add listener if disabled
if (!enabled) {
return;
}
// Get the target element
const targetElement = getTargetElement(element);
// Don't add listener if element is null
if (!targetElement) {
return;
}
// Internal handler that calls the ref (always latest handler)
const internalHandler = (event: Event) => {
handlerRef.current(event);
};
// Build event listener options
const eventOptions: AddEventListenerOptions = {
capture,
once,
};
// Only set passive if explicitly provided (respect browser defaults)
if (passive !== undefined) {
eventOptions.passive = passive;
}
// Add event listener
targetElement.addEventListener(eventName, internalHandler, eventOptions);
// Cleanup
return () => {
targetElement.removeEventListener(eventName, internalHandler, {
capture,
});
};
}, [eventName, element, enabled, capture, passive, once]);
}
|