Welcome to part-11 of the series. 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.
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.
Now, in the browser both of them 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().
It works as expected and show the Even/Odd text beside Counter One and changes with it.
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.
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.
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.
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.
This completes part-11 of the series.
You can find the code for the same in this github repo.