React Hooks tutorials for beginners-11

Image for post
Image for post
Hooks

Welcome to part-11 of the series. You can find part-10 here. We will learn about the other performance optimization hooks —useMemo in this part.

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.

Image for post
Image for post
App.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.

Image for post
Image for post
Counter.js

Now, in the browser both of them changes independently.

Image for post
Image for post
Changes 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().

Image for post
Image for post
isEven

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

Image for post
Image for post
Even 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.

Image for post
Image for post
while 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.

Image for post
Image for post
Slowness

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.

Image for post
Image for post
Counter,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.

Image for post
Image for post
Issue solved

This completes part-11 of the series. You can find part-12 here.

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

Written by

UI Lead- ReactJS, JavaScript and everything in-between.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store