Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using useMemo instead of React.memo syntax issue

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.

like image 507
Pete Avatar asked Apr 02 '19 02:04

Pete


People also ask

Is useMemo and React memo same?

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.

Does useMemo prevent re render?

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.

When should we not use useCallback and useMemo?

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.


1 Answers

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 (either a or b) 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.

like image 51
jayarjo Avatar answered Oct 09 '22 13:10

jayarjo