Hooks
useEventListener()

useEventListener()

It uses the addEventListener (opens in a new tab) method to be called whenever a specified event is delivered to the target.

Usage

import { useRef } from 'react';
import { useEventListener } from '@norr/hooks';
 
const Component = () => {
  const buttonRef = useRef<HTMLButtonElement>(null);
 
  const handleScroll = (event: Event) => {
    console.log('Window scrolled.', event);
  };
 
  const handleClick = (event: MouseEvent) => {
    console.log('Button clicked.', event);
  };
 
  // Window based event
  useEventListener({
    type: 'scroll',
    listener: handleScroll,
  });
 
  // Element based event
  useEventListener({
    type: 'click',
    listener: handleClick,
    target: buttonRef,
  });
 
  return (
    <button type="button" ref={buttonRef}>
      Click me.
    </button>
  );
};