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);
});
Basic usage of useMemoizedFn hook.
Current ParentComponent - count: 0
Current SubComponent - renderCount: 1
Current SubComponent - renderCount: 1
Property | Description | Type | Default |
---|---|---|---|
fn | Function that requires persistence | (...args: any[]) => any | - |
Property | Description | Type |
---|---|---|
fn | Function (the function reference never changes) | (...args: any[]) => any |