Skip to main content

useEventListener

지정된 요소에 이벤트 리스너를 추가하고, 컴포넌트가 언마운트될 때 자동으로 제거합니다.


Code

🔗 실제 구현 코드 확인

Interface

typescript
type EventListenerAvailableElement =
| Window
| Document
| HTMLElement
| SVGElement
| MediaQueryList;

type TargetElement<T extends EventListenerAvailableElement> =
| T
| RefObject<T | null | undefined>;
typescript
// Window Event based useEventListener interface
function useEventListener<K extends keyof WindowEventMap>(
element: Window,
type: K,
listener: (event: WindowEventMap[K]) => void,
options?: AddEventListenerOptions
): void;

// Document Event based useEventListener interface
function useEventListener<K extends keyof DocumentEventMap>(
element: Document,
type: K,
listener: (event: DocumentEventMap[K]) => void,
options?: AddEventListenerOptions
): void;

// MediaQueryList Event based useEventListener interface
function useEventListener<K extends keyof MediaQueryListEventMap>(
element: MediaQueryList,
type: K,
listener: (event: MediaQueryListEventMap[K]) => void,
options?: AddEventListenerOptions
): void;

// Element Event based useEventListener interface
function useEventListener<
K extends keyof HTMLElementEventMap,
T extends HTMLElement
>(
element: TargetElement<T>,
type: K,
listener: (event: HTMLElementEventMap[K]) => void,
options?: AddEventListenerOptions
): void;

// SVGElement Event based useEventListener interface
function useEventListener<
K extends keyof SVGElementEventMap,
T extends SVGElement
>(
element: TargetElement<T>,
type: K,
listener: (event: SVGElementEventMap[K]) => void,
options?: AddEventListenerOptions
): void;

Usage

typescript
import { useState, useRef } from 'react';
import { useEventListener } from '@modern-kit/react';

const Example = () => {
const [number, setNumber] = useState(0)
const buttonRef = useRef<HTMLButtonElement | null>(null);

useEventListener(document, 'click', () => {
console.log(number);
})

useEventListener(buttonRef, 'click', () => {
setNumber(number + 1);
})

return (
<div>
<p>number: {number}</p>
<button ref={buttonRef}>숫자 더하기</button>
</div>
);
};

Example