I need to make a demonstration of using React Hooks useMemo. I have working code that is as follows that does what I want:
const SpeakerCardDetail = React.memo( ({id,...
I found a link that shows that I could use syntax more like this but I can't figure it out exactly.
This is as far as I got:
const SpeakerDetail = React.useMemo(() => { ({ id,
Clearly not it though. I do get that React.memo solves the problem but I do need to show useMemo in action and am hoping there is an alternative syntax that I can use.
The useMemo is used to memoize values, React. memo is used to wrap React Function components to prevent re-renderings. The useCallback is used to memoize functions.
1. Memoization using useMemo() and UseCallback() Hooks. Memoization enables your code to re-render components only if there's a change in the props. With this technique, developers can avoid unnecessary renderings and reduce the computational load in applications.
UseCallback is used to optimize the rendering behavior of your React function components, while useMemo is used to memoize expensive functions to avoid having to call them on every render. As a standard construction of hooks, those two solutions are not so different.
React.memo
and React.useMemo
are not equivalent at all (don't rely on naming similarity). Here's a quote from React.memo
doc:
React.memo
is a higher order component.
So it's a HOC that can optimize rendition of your component given that it renders the same output with the same properties.
React.useMemo
on the other hand is more generic and returns a memoized value:
Pass a “create” function and an array of dependencies.
useMemo
will only recompute the memoized value when one of the dependencies (eithera
orb
) has changed.
const memoizedValue = useMemo( () => computeExpensiveValue(a, b), [a, b] );
And while it can be hacked to be used instead of React.memo
, it's not its purpose and it will add to the confusion more than it will help. useMemo
is a hook and is subject to the certain usage rules.
And there's this warning as well:
In the future, React may choose to “forget” some previously memoized values and recalculate them on next render, e.g. to free memory for offscreen components. Write your code so that it still works without
useMemo
— and then add it to optimize performance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With