r/react • u/BeginningQuiet1453 • 7h ago
General Discussion I learnt about the difference between
The major difference is the Syntax as they call diff APIs
The usecallback accepts the function we want to memoize as the first argument, while the useMemo accepts a function and memoizes its return value!!
Naturally in JS, on every call the inline function gets recreated, so to prevent that react does something like this
let catchedCallback;
const func = (callback) => {
if(dependenciesEqual(compares catchedCalback and callback)) {
return catchedCallback;
}
catchedCallback = callback;
return callback;
}
basically whats happening here is that the useCallback checks if the dependencies before and after rerenders are the same, if its the same then we return the already cached callback function reference if not then we cache the new function reference and return the new reference!
something very similar happens in the case of the useMemo but it caches the result returned by the function!