Understanding useMemo hooks
Since React 16.8. we are introduced to a new tool called Hooks which let us use state and other React features in functional-based components without using a class. In this article, we will look after one of the underused react hooks i.e useMemo.
useMemo hooks accept a function and a list of dependencies and return the memoized value returned by the passed function. It recalculated the value only when one of its dependencies change. It is useful to avoid expensive calculations on every render when the returned value is not going to change.
Syntax:
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
Let us understand useMemo hooks through some examples
Example 1:
Issue :
Above we can see that the useEffect runs and logs Hello dear
I click on the +
button even though dependency calculation
is the same in value i.e [1, 2, 3] in our case. This is caused due to phenomenon known as Referential Equality.
Referential Equality
First of all, in javascript, we have to understand that two Array or Object are not exactly equal even though they share the same value.
Solution
We can solve the above issue by using the useMemo hooks of react. The implementation of the useMemo hook for the above code is given below.
Here Referential Equality is been resolve by the use of useMemo and its memorized return value which help us to avoid unnecessary re-run of useEffect hook.
Example 2:
Let us see another example and modify the above code a bit.
Issue :
In this code, we just need to remember two things. First, there are three functions addTodo
, expensiveCalculation,
and increment
. And expensiveCalculation the
function is just effect by increment
, addTodo
doesn’t have anything to do with expensiveCalculation
.
Here we can see that expensiveCalculation
is running whenever we click Add Todo
button event on click Add Todo
button it has not thing to do with the expensiveCalculation
function. This issue is caused because on react app runs all the code in the Component whenever there is a change in any state of the component which lets const calculation = expensiveCalculation(count);
to execute when we click Add Todo
which allowed changing the state of todo
.
Solution
Above issue avoid using useMemo hooks. The implementation of the useMemo hook for the above code is given below.
Here we can see that expensiveCalculation
is not running on click Add Todo
Button event. The above issue is addressed because of the useMemo hook, as I mention above useMemo recalculated the value only when one of its dependencies change. Here in our case, the dependency count is not changed, so the useMemo hook doesn’t allow a rerun expensiveCalculation
.
Conclusion
Hence we conclude to use useMemo hooks whenever we need to avoid expensive calculations and unnecessary re-rendering of child components to enhance and optimize our react application performance.
Thank you!!!