Skip to content

Instantly share code, notes, and snippets.

@andycarrell
Created April 1, 2020 02:04
Show Gist options
  • Save andycarrell/998c1dfdb25dadcb4560b8bb8e802192 to your computer and use it in GitHub Desktop.
Save andycarrell/998c1dfdb25dadcb4560b8bb8e802192 to your computer and use it in GitHub Desktop.
function useConstantCallback(fn) {
// store a copy of the function
const copyOfFunction = React.useRef(fn);
// create a function that always has the same reference (won't trigger a useEffect)
const alwaysTheSameFunction = React.useCallback(
(...args) => copyOfFunction.current(...args),
[],
);
// update the copy each render so it is scoped to the current state/props of that render
React.useLayoutEffect(() => {
copyOfFunction.current = fn;
});
return alwaysTheSameFunction;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment