Last active
March 16, 2023 02:18
-
-
Save Codennnn/1a29d21fe4a1be6faaf547db33219573 to your computer and use it in GitHub Desktop.
对目标函数进行 memoized,并保证每次调用目标函数时都是最新的。
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 { useRef } from 'react'; | |
type AnyFunction = (...args: any[]) => any; | |
/** | |
* 对目标函数进行 memoized,并保证每次调用目标函数时都是最新的。 | |
* | |
* 当你需要把函数加入诸如 `useEffect` 的 dependencyList,而又不希望函数的 update/recreate 造成 hook 执行,就需要用到此方法。 | |
*/ | |
export function useEvent<T extends AnyFunction | undefined>(callback: T): T { | |
const funcRef = useRef<T>(); | |
funcRef.current = callback; | |
const stableRef = useRef<T>(); | |
if (!stableRef.current) { | |
stableRef.current = ((...args) => { | |
return funcRef.current?.(...args); | |
}) as T; | |
} | |
return stableRef.current; | |
} |
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
type CallbackFun = (...args: any[]) => any; | |
/** | |
* 对目标函数进行 memoized,并保证每次调用目标函数时都是最新的。 | |
* | |
* 当你需要把函数加入诸如 `useEffect` 的 dependencyList,而又不希望函数的 update/recreate 造成 hook 执行,就需要用到此方法。 | |
*/ | |
export function useMemoizedFn<T extends CallbackFun | undefined>(callback: T): CallbackFun { | |
const funcRef = useRef<T>(); | |
funcRef.current = callback; | |
return useCallback<CallbackFun>((...args) => { | |
if (funcRef.current) { | |
return funcRef.current(...args); | |
} | |
}, []); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment