Created
April 1, 2020 02:04
-
-
Save andycarrell/998c1dfdb25dadcb4560b8bb8e802192 to your computer and use it in GitHub Desktop.
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 characters
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