I am reading this article about memoization in React, and I wonder how can I translate and use useMemo instead of useCallback hook. In particular for this example:
<Child name={ useCallback(() => {console.log('Really Skinny Jack')}, []) } />
Where Child component looks like this:
export default React.memo(function Child({ name }) {
console.log("Child component");
return (
<>
{name()}
<div>Child component</div>
</>
);
});
If I try to replace this with useMemo:
<Child
name={useMemo(() => {
console.log("useMemo");
}, [])}
/>
I get an error:
TypeError name is not a function
I also tried like this:
{useMemo(
<Child
name={() => {
console.log("useMemo");
}}
/>,
[]
)}
But, then I get:
TypeError nextCreate is not a function
So, I how am I suppose to replace useCallback with useMemo in this example?
With
useMemo, you can do it like thisWith
useMemo, whatever you return from theuseMemo's callback will be memoized. On the other hand,useCallbackis used to memoize functions only.Some key differences to note
useMemoUsed to memoize functions, arrays, objects, etc.
useCallbackUsed to memoize functions
React.memoA Higher-Order Component to memoize React components