Created
February 4, 2021 20:16
-
-
Save amcdnl/f6b80ba5912d7783bb70f3388dc1225e to your computer and use it in GitHub Desktop.
Revisions
-
amcdnl created this gist
Feb 4, 2021 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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]); }