use-window-event
use-window-event
컴포넌트가 마운트될 때 window 객체에 이벤트 리스너를 추가하고, 언마운트될 때 제거하는 훅이에요.
출처: 문서
본문
사용법 (Usage)
use-window-event 훅은 컴포넌트가 마운트될 때 window 객체에 이벤트 리스너를 추가하고 언마운트될 때 제거해요:
import { useEffect } from 'react';
import { useWindowEvent } from '@mantine/hooks';
const handler = (event: KeyboardEvent) => console.log(event);
// regular way
useEffect(() => {
window.addEventListener('keydown', handler);
return () => window.removeEventListener('keydown', handler);
}, []);
// with use-window-event hook
useWindowEvent('keydown', handler);
예시 (Example)
Mantine 문서 사이트에서 macOS의 ⌘ + K 또는 Windows와 Linux의 Ctrl + K로 검색에 포커스하는 예시예요:
import { useRef } from 'react';
import { useWindowEvent } from '@mantine/hooks';
function Demo() {
const inputRef = useRef<HTMLInputElement>(null);
useWindowEvent('keydown', (event) => {
if (event.code === 'KeyK' && (event.ctrlKey || event.metaKey)) {
event.preventDefault();
inputRef.current?.focus();
}
});
return <input ref={inputRef} />;
}
정의 (Definition)
이 훅은 window.addEventListener 함수와 동일한 정의를 가져요:
function useWindowEvent<K extends keyof WindowEventMap>(
type: K,
listener: K extends keyof WindowEventMap
? (this: Window, ev: WindowEventMap[K]) => void
: (this: Window, ev: CustomEvent) => void,
options?: boolean | AddEventListenerOptions
): void;