D
D
Durin Qurkingo2019-07-21 21:06:49
React
Durin Qurkingo, 2019-07-21 21:06:49

How to avoid overusing useMemo?

The documentation states the following:
useMemo will only recalculate the stored value when one of the dependencies has changed. This optimization helps avoid costly calculations on every render.
Sounds good, doesn't it? But in order to optimize performance, one must be sure that the calculations are more expensive than using the Memo itself before using it. Any suggestions for when to avoid using Memo?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2019-07-21
@Sagund

useMemo uses a superficial dependency comparison, just as each render defines a callback function if it is written in the body of the component.
The same data filtering or rendering lists usually cost more. You can look at the source code of the hooks and evaluate all the internal calls that the library makes.
Keep in mind that there is a note in the documentation that React can forget your value, so this hook should only be used for memorization.
I saw code examples when useMemo was used both to create a context and to update the state. This should not be done, as the context created in this way may be lost or the state may be reset.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question