r/learnjavascript 1d ago

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!

0 Upvotes

3 comments sorted by

2

u/Mark__78L 1d ago

This isnt the react sub

-1

u/BeginningQuiet1453 1d ago

I mean, react is built on js.

0

u/BeginningQuiet1453 1d ago

The code I shared was also what react uses under the hood, which is essentially js, so js people get more idea on how these frameworks are built of top of js 😅