Photo by Daniel Eledut on Unsplash

Analyses on Re-render of React Components — 3 (useMemo)

Several methods are used to obtain a performance out of the normal rendering logic of the React components. In this article, we will focus on the useMemo.

Onur Dayıbaşı
2 min readOct 8, 2022

--

In the subjects I have explained so far (Performance1 and Performance2), the main goal has been the prevention of the component re-render. In sum;

  • We could prevent unnecessary rendering of the component with the ClassComponent shoudComponentUpdate.
  • We could prevent unnecessary rendering of the component with the PureComponent or React.memo. We could ensure with the useCallback that the callback references are the same and ensure effective running of the React.memo

As you can see, the above mentioned approaches are intended to prevent repetitive render of the component.

Then, if a very time-consuming, IO etc. value within a component takes the returning function, the same parameters, how can we prevent the repetitive running of them? The answer is → the useMemo.

https://reactjs.org/docs/hooks-reference.html#usememo

The useMemo ensures prevention of recall of the previously called values when a value-returning function is called with the same parameters and ensures returning to the cached value.

Sometimes it is more meaningful to control the function instead of controlling the render of the following component. Think that we do not memoize the computeExtensiveValue, this function will also be operated in unnecessary situations.

When we run the following code, the function obtaining the computeExpensiveValue is called repetitively.

This time let’s memoize the function with useMemo; in this way, we can save the value created at any place.

And you can see that the computExtensiveValue is not called repetitively with the method we have obtained.

References

--

--