back to all posts

React Hooks Tutorials -11

by Nabendu Biswas / December 28th, 2020

#react #beginners #hooks
Series: React-Hooks

Welcome to part-11 of the series. We will learn about the other performance optimization hooks, useMemo in this part.

useMemo hook

To understand the need of performance, we will create a small project first. So, go ahead and create new React project memo-hook by the below command

    npx create-react-app memo-hook

Now, in App.js include the Counter and remove the earlier default code.

App.jsApp.js

Now, create a file Counter.js inside a components folder. The content for it is below. It contains two state variables and then two button to increment the same.

Counter.jsCounter.js

Now, in the browser both of them changes independently.

Changes independentlyChanges independently

Now, we have a simple requirement where we show whether the Counter one is even or odd. We can do it easily by creating a function isEven().

isEvenisEven

It works as expected and show the Even/Odd text beside Counter One and changes with it.

Even oddEven odd

But in real world scenarios, the some functions takes a lot of time to run. We will now include some slowness in our function, by running a while loop for 2000000000 times.

while loopwhile loop

Now, click on Count One button and we will see the slowness. But the slowness is also visible, when we click on the Count Two button.

SlownessSlowness

The Count One slowness is obvious but the count two slowness, is because every time a state variable is changed the whole component is re-rendered which include the slow isEven() funtion.

To fix this, we will use the useMemo hook on the isEven function and give the variable counterOne to it in a array. So, it will run only if the state variable counterOne changes.

Also, note that isEven is a now a reference to a function, so no brackets.

Counter,jsCounter,js

Now, go back to localhost and click on Count One button and we will see the slowness. But the slowness is not anymore, when we click on the Count Two button.

This happens because when the counterTwo state variable changes and the component re-renders, it uses the cached value of isEven function to display whether the Counter One is odd or even.

Issue solvedIssue solved

This completes part-11 of the series.

You can find the code for the same in this github repo.

Nabendu Biswas