Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use React.memo or useMemo with a semantic guarantee?

The documentation for useMemo says:

You may rely on useMemo as a performance optimization, not as a semantic guarantee. 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

React.memo and shouldComponentUpdate have similar warnings.

I have a case, however, where I want a functional component not to update under certain conditions. I am looking for memo-like functionality not for performance, but for the semantic guarantee of there being no update given some conditions. How do I address this issue?

like image 765
Dmitry Minkovsky Avatar asked Sep 17 '19 15:09

Dmitry Minkovsky


People also ask

What is the difference between useMemo and React memo?

Now you have a good understanding of both of them. Use React. memo to memoize an entire component. Use useMemo to memoize a value within a functional component.

How will you use memo in React?

The React useMemo Hook returns a memoized value. Think of memoization as caching a value so that it does not need to be recalculated. The useMemo Hook only runs when one of its dependencies update. This can improve performance.


1 Answers

Store the values you need to memoize in a useRef()

like image 96
Will Jenkins Avatar answered Oct 26 '22 20:10

Will Jenkins