Function useEventListener

  • Custom React hook that adds an event listener to a specified target element.

    This hook manages the event listener lifecycle, attaching it to the target element when the component mounts and removing it when the component unmounts or when dependencies change. It also supports disabling the listener based on a condition or a boolean flag.

    Example

    const MyComponent = () => {
    const ref = useRef<HTMLDivElement>(null);

    const handleClick = () => {
    console.log('Div clicked!');
    };

    useEventListener({
    ref,
    target: 'click',
    listener: handleClick,
    });

    return <div ref={ref}>Click me!</div>;
    };

    Type Parameters

    • Target extends keyof HTMLElementEventMap

    • Listener extends ((event) => void)

    Parameters

    Returns void