Skip to content

Instantly share code, notes, and snippets.

@amcdnl
Created February 4, 2021 20:16
Show Gist options
  • 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