Last active
October 30, 2019 19:57
-
-
Save zetorama/57b9715e0303967d3fcd18510204b248 to your computer and use it in GitHub Desktop.
useCurrent*/useBound* — hooks to bind callbacks to "whatever current value is"
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
import { useRef, useCallback, useEffect } from 'react' | |
function useCurrentGetter(value) { | |
const refValue = useRef(value); | |
useEffect(() => { | |
refValue.current = value; | |
}, [value]); | |
return useCallback(() => refValue.current, [refValue]); | |
} | |
function useCurrentCallback(callback) { | |
const getCallback = useCurrentGetter(callback); | |
return useCallback((...args) => getCallback()(...args), [getCallback]); | |
} | |
function useBoundCallback(callback, args) { | |
const currentCallback = useCurrentCallback(callback); | |
const getArgs = useCurrentGetter(args); | |
return useCallback( | |
(...runtimeArgs) => { | |
const boundArgs = getArgs(); | |
return currentCallback(...boundArgs, ...runtimeArgs); | |
}, | |
[currentCallback, getArgs] | |
); | |
} | |
function useBoundEffect({ args, effect, deps = [] }) { | |
const callback = useBoundCallback(effect, args); | |
return useEffect(callback, [callback, ...deps]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example, how it simplifies
gaearon's useInterval()
:Example, how it allows bind effects to current values: