본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

useEventListener

원문 보기 위키 갱신

useEventListener 훅은 DOM 이벤트 리스너를 선언적으로 등록하고, 컴포넌트가 언마운트될 때 자동으로 정리(cleanup)해 주며, 필요에 따라 수동으로 제어할 수 있는 bind/unbind 쌍까지 제공해요. 리스너의 등록과 해제를 직접 관리해야 하는 번거로움을 없애 주는 아주 유용한 훅이에요.

출처: 문서

본문

사용법 (Usage)

import { useEventListener } from '@primereact/hooks/use-event-listener';
const [bind, unbind] = useEventListener({
    target: 'document',
    type: 'click',
    listener: (event) => console.log(event),
    when: true
});

when이 true일 때 리스너가 등록되고, 언마운트 시 자동으로 해제돼요. 언마운트하지 않고 일시적으로 동작을 멈추고 싶다면 when 값을 토글하면 돼요.

옵션 (Options)

  • target, 'document' | 'window' | 'body' | HTMLElement | (() => HTMLElement) | Ref | string | null. 셀렉터 문자열, ref, 또는 요소를 필요할 때 해석해 주는 함수를 모두 받아요.
  • type, 이벤트 이름이에요. 예: 'click', 'keydown', 또는 커스텀 이벤트.
  • listener, 핸들러 함수예요.
  • options?, 표준 addEventListener 옵션(capture, passive, once)을 받아요.
  • when?, 기본값은 true이며, false로 설정하면 비활성화돼요.

수동 제어 (Manual control)

반환되는 [bind, unbind]를 이용하면 명령형(imperative)으로 리스너를 등록/해제할 수 있어요. prop 값이 아니라 사용자의 동작에 반응해서 리스닝을 시작하고 싶을 때 유용해요:

<button onClick={() => bind()}>Listen</button>
<button onClick={() => unbind()}>Stop</button>

더 알아보기 (Learn more)