useMemo: Basic Usage

When should we use useMemo?

Sebastián Cáceres
Understanding of React Hooks
1 min readJun 26, 2020

--

Sometimes we may have noticed that React Components may trigger the render method multiple times unnecessarily, this happens for example if we change the state or if a prop changes…

Sometimes we may not really care about this… But if there is a heavy-load function executing inside the component we may be in trouble.

For example:

The function generateRandomNames is triggering everytime the component wants to re-render. It takes a lot of resources… and makes our UI slow, everytime we change the state name. This function will execute and the numbers shown in the screen will change. How can we stop this?

Let’s wrap our heavy-load operations under the hook useMemo!

Now we will only generate numbers once, when the component is just loaded. When we update the name state the numbers variable won’t change.

That’s it!

--

--