Last active
July 28, 2021 16:53
-
-
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.
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
/** | |
* 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use
arguments
ifparameters
don't work.