Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

useEventListener #1

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Commits on Aug 2, 2022

  1. useEventListener

    import { useRef, useEffect } from 'react'
    
    interface IEventProps {
      eventType: keyof GlobalEventHandlersEventMap
      listener: Function,
      target: Window | Document,
      options?: boolean | AddEventListenerOptions | undefined
    }
    
    const useEventListener = ({
      eventType = 'scroll',
      listener = () => null,
      target = window,
      options = undefined
    }: IEventProps) => {
      const savedListener = useRef<Function>();
    
      useEffect(() => {
        savedListener.current = listener;
      }, [listener]);
    
      useEffect(() => {
        if (!target?.addEventListener) return;
    
        const eventListener = (event: any) => savedListener?.current?.(event);
    
        target?.addEventListener?.(eventType, eventListener, options);
    
        return () => {
          target?.removeEventListener(eventType, eventListener, options);
        };
      }, [eventType, target, options]);
    };
    
    export default useEventListener;
    FrankChinedu authored Aug 2, 2022
    Configuration menu
    Copy the full SHA
    0e8b4e9 View commit details
    Browse the repository at this point in the history