useMemoizedFn

A hook that is able to persist functions. In theory, useMemoizedFn could be used to replace useCallback.

In some scenarios, we need to use useCallback to cache a function, but when deps (the second parameter) changes, the function will be regenerated, thus causing the function reference to change.

// usage
const fn = useMemoizedFn<T>(fn: T): T;
const [count1, setCount1] = useState("");

// func function reference will change once count is changed
const func = useCallback(() => {
  console.log(count1);
}, [count1]);

By using useMemoizedFn, you can omit the second parameter deps, and ensure that the function reference never changes.

const [count2, setCount2] = useState("");

// func function reference will never change
const func = useMemoizedFn(() => {
  console.log(count2);
});

Examples

Basic usage of useMemoizedFn hook.

Performance Improvement - useMemoizedFn can be used to optimize performance

API

Params

PropertyDescriptionTypeDefault
fnFunction that requires persistence(...args: any[]) => any-

Result

PropertyDescriptionType
fnFunction (the function reference never changes)(...args: any[]) => any