React 18 how to Automatically optimize callbacks in compiler level ?
Please check this package https://github.com/oney/kill-use-callback
depFn
is not a React hook that needs to depend on React lifecycle, sodepFn
can be used anywhere like in a condition or in a loop.
depFn
makes it possible to optimize any callbacks in compiler(e.g. babel) by automatically collecting all values to deps array. Therefore, developers don't have to write useCallback
by themselves anymore, and we can totally remove useCallback
hook in React core.
The key concept of depFn
is:
If two closures have the same "function body code", and the same "environment" (or context) which actually means the dependency of values or references, these two closures can be considered as equal
Don't forget this in the doc:
In the future, a sufficiently advanced compiler could create this array automatically.
To be clear, what I mean is when developers write the code like
function App({items, text}) {
const getText = text.length === 10 ? undefined
: (prefix) => `${prefix}: ${text}`;
useEffect(() => { /* ... */ }, [getText]);
return (<div>{items.map(item => (
<Child getText={() => `${item}: ${text}`} />
))}</div>);
}
The compiler collects deps array and wraps callback with depFn
automatically:
function App({items, text}) {
const getText = text.length === 10 ? undefined
: depFn((prefix) => `${prefix}: ${text}`, [text]);
useEffect(() => { /* ... */ }, [getText]);
return (<div>{items.map(item => (
<Child getText={depFn(() => `${item}: ${text}`, [text])} />
))}</div>);
}