Skip to content

Instantly share code, notes, and snippets.

@amcdnl
Created February 4, 2021 20:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amcdnl/f6b80ba5912d7783bb70f3388dc1225e to your computer and use it in GitHub Desktop.
Save amcdnl/f6b80ba5912d7783bb70f3388dc1225e to your computer and use it in GitHub Desktop.
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]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment