Skip to content

Instantly share code, notes, and snippets.

@amcdnl
Created February 4, 2021 20:16
Show Gist options
  • Select an option

  • Save amcdnl/f6b80ba5912d7783bb70f3388dc1225e to your computer and use it in GitHub Desktop.

Select an option

Save amcdnl/f6b80ba5912d7783bb70f3388dc1225e to your computer and use it in GitHub Desktop.

Revisions

  1. amcdnl created this gist Feb 4, 2021.
    27 changes: 27 additions & 0 deletions useEventCallback.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,27 @@
    import { useRef, useEffect, useCallback } from 'react';

    export type noop = (...args: any[]) => any;

    /**
    * Stable callback
    *
    * References:
    * - https://github.com/facebook/react/issues/14099
    * - https://reactjs.org/docs/hooks-faq.html#how-to-read-an-often-changing-value-from-usecallback
    * - https://gist.github.com/rolandcoops/4364be2eff3586b0f8f3d0c10dc3be61
    * - https://github.com/alibaba/hooks/blob/master/packages/hooks/src/usePersistFn/index.ts
    */
    export function useEventCallback(fn: noop, dependencies: any[]) {
    const ref = useRef<noop>(() => {
    throw new Error('Cannot call an event handler while rendering.');
    });

    useEffect(() => {
    ref.current = fn;
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [fn, ...dependencies]);

    return useCallback((...args) => {
    return ref.current(...args);
    }, [ref]);
    }