Skip to content

Instantly share code, notes, and snippets.

@danielearwicker
Created May 15, 2021 10:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielearwicker/9093ea3fdef41398ccd2a271ac6c221e to your computer and use it in GitHub Desktop.
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
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