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,useCallback
is used to memoize functions only.Some key differences to note
useMemo
Used to memoize functions, arrays, objects, etc.
useCallback
Used to memoize functions
React.memo
A Higher-Order Component to memoize React components