Skip to content

Instantly share code, notes, and snippets.

@Codennnn
Last active March 16, 2023 02:18
Show Gist options
  • Save Codennnn/1a29d21fe4a1be6faaf547db33219573 to your computer and use it in GitHub Desktop.
Save Codennnn/1a29d21fe4a1be6faaf547db33219573 to your computer and use it in GitHub Desktop.
对目标函数进行 memoized,并保证每次调用目标函数时都是最新的。
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;
}
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