Skip to content

Instantly share code, notes, and snippets.

@karol-majewski
Last active July 28, 2021 16:53
Show Gist options
  • Save karol-majewski/320182161689b58a87373fa40d1a0004 to your computer and use it in GitHub Desktop.
Save karol-majewski/320182161689b58a87373fa40d1a0004 to your computer and use it in GitHub Desktop.
Forget about stale closures once for all. Inspired by https://stackoverflow.com/a/67270735/10325032.
/**
* When two functions have the same signature, but are not equal.
*
* Fixes the "'T' could be instantiated with a different subtype of constraint" ts(2322) type error.
*
*/
type WrapperFunction<T extends AnyFunction> = (...parameters: Parameters<T>) => ReturnType<T>;
/**
* Prevents stale closures.
*
* @see https://stackoverflow.com/a/67270735/10325032
*/
export function useFunction<T extends AnyFunction>(fn: T): WrapperFunction<T> {
const ref = React.useRef<T>(fn);
ref.current = fn;
function wrapper(this: ThisParameterType<T>, ...parameters: Parameters<T>): ReturnType<T> {
return ref.current.apply(this, parameters);
}
return React.useRef(wrapper).current;
}
@karol-majewski
Copy link
Author

Use arguments if parameters don't work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment