RUI.next

Hooks
useMemoizedFn

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;
// 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]);
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);
});
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

Current ParentComponent - count: 0


Click to view the re-render of SubComponent

Pass prop to SubComponent by useCallback

Current SubComponent - renderCount: 1


Click to show the count of ParentComponent

Pass prop to SubComponent by useMemoizedFn

Current SubComponent - renderCount: 1


Click to show the count of ParentComponent

API

Params

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

Result

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