Skip to content

Instantly share code, notes, and snippets.

@just-boris
Created December 12, 2020 15:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save just-boris/c90bc9031b05c22f2985511e4e294f99 to your computer and use it in GitHub Desktop.
Save just-boris/c90bc9031b05c22f2985511e4e294f99 to your computer and use it in GitHub Desktop.
import { useCallback, useEffect, useRef } from 'react';
/**
* A callback that stays stable between renders even as the dependencies change.
*
* @see https://reactjs.org/docs/hooks-faq.html#how-to-read-an-often-changing-value-from-usecallback
*/
export function useStableEventHandler<T extends (...args: any[]) => any>(fn: T): T {
const ref = useRef<T>();
useEffect(() => {
ref.current = fn;
}, [fn]);
return useCallback(((...args) => ref.current?.apply(undefined, args)) as T, [ref]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment