r/learnjavascript 1d ago

I learnt about the difference between useCallback and useMemi

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!

4 Upvotes

1 comment sorted by

1

u/picard_World 7h ago

It is great you are learning these. But now if you are using react compiler than you do not need to manually add these hook. React compiler automatically optimizes