Created
May 15, 2021 10:30
-
-
Save danielearwicker/9093ea3fdef41398ccd2a271ac6c221e to your computer and use it in GitHub Desktop.
usePartialCall - binding more args to end of a callback, avoid re-rendering a pure react component
This file contains 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 { useEffect, useRef, useMemo } from "react"; | |
type Args = readonly unknown[]; | |
function usePartialCall<A extends Args, M extends Args, R>( | |
f: (...args: [...A, ...M]) => R, | |
...moreArgs: M | |
) { | |
const ref = useRef(moreArgs); | |
useEffect( | |
() => { | |
ref.current = moreArgs; | |
}, | |
// linter is confused: moreArgs is an array and we want | |
// to trigger effect if any of its elements change. | |
// eslint-disable-next-line react-hooks/exhaustive-deps | |
moreArgs | |
); | |
return useMemo( | |
() => (...a: A) => f(...a, ...ref.current), | |
// linter chokes on TS and thinks A is a runtime value. | |
// eslint-disable-next-line react-hooks/exhaustive-deps | |
[f] | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment