@tremendous/help
    Preparing search index...

    Function useEventListener

    Custom hook that adds an event listener to a target element or window.

    This hook takes an event name, a handler function, and optionally a ref to a target element. It ensures the event listener is properly added and removed when dependencies change.

    The type of the window event name.

    The type of the HTMLElement event name.

    The type of the target element, or void if no element is provided.

    The name of the event to listen for.

    The function to handle the event.

    Optional ref object of the target element.

    const buttonRef = useRef<HTMLButtonElement>(null);
    useEventListener('click', (event) => {
    console.log('Button clicked:', event);
    }, buttonRef);
    • Custom hook that adds an event listener to a target element or window.

      This hook takes an event name and a handler function, and optionally a ref to a target element. It ensures the event listener is properly added and removed when dependencies change.

      Type Parameters

      • K extends keyof WindowEventMap

        The type of the event name.

      Parameters

      • eventName: K

        The name of the event to listen for.

      • handler: (event: WindowEventMap[K]) => void

        The function to handle the event.

      Returns void

      useEventListener('resize', (event) => {
      console.log('Window resized:', event);
      });
    • Custom hook that adds an event listener to a target element or window.

      This hook takes an event name and a handler function, and optionally a ref to a target element. It ensures the event listener is properly added and removed when dependencies change.

      Type Parameters

      • K extends keyof HTMLElementEventMap

        The type of the event name.

      • T extends HTMLElement = HTMLDivElement

        The type of the target element.

      Parameters

      • eventName: K

        The name of the event to listen for.

      • handler: (event: HTMLElementEventMap[K]) => void

        The function to handle the event.

      • element: RefObject<T>

      Returns void

      useEventListener('resize', (event) => {
      console.log('Window resized:', event);
      });