The useMemo hook is used to return a
cached value
in order to save any re-computation overhead.
It works similarly to the useCallback hook
🔍
Many tutorials on the internet will extensively cover the useState hook
or the useEffect hook
, however, many tutorials do not get into the more nuanced React hooks such as useMemo
.
Before getting into😸 the technical details of the useMemo hook
, it’s important to understand the purpose behind using the useMemo hook
.
Purpose 💫
As your application scales, performance issues become more and more evident. While React is very well optimized and fast out-of-box, it is important to know the instruments it provides to make your code even faster😯. One of such instruments is React.useMemo hook
and its sidekick,React.useCallback
.
This article will help you understand what useMemo
hook is and how it works. What problem does useMemo solve.
React useMemo hook🪝
useMemo()
is a built-in React hook that accepts ✌️two arguments — a function
compute that computes a result and the dependencies array
:
const memoizedResult = useMemo(compute, dependencies);
Let us try to get the essence of the useMemo hook
.
During the first rendering,
useMemo(compute, dependencies)
invokes the compute function, which is the first argument, memoizes the calculation result, and returns it to the component.If during the next renderings the dependencies change, then
useMemo()
invokes compute, memoizes the new value, and returns it. But if dependencies don't change during re-rendering, thenuseMemo()
doesn't invoke compute but returns the memoized value.
React
useMemo
helps developers memoize expensive functions so that they don't have to retrieve information whenever they need to change input. The useMemo hook recomputes the specific memoized value when a user changes an input. It saves time by stopping the rerunning functions in each computation.
What problem does useMemo solve?🕵️♀️
useMemo
will call the function and return its return value. Then, every time you call useMemo again, it will first check if any dependencies have changed. If not, it will return the cached return value
, not calling the function. If they have changed, useMemo
will call the provided function again and repeat the process.
This should remind you of the useEffect hook:, both useMemo and useEffect accept lists of dependencies. The only difference is that useEffect is intended for side-effects (hence the name), while functions in useMemo are supposed to be pure and with no side-effects😮.
useMemo
is used to speed up slow functions in React applications. It optimizes the functions and reduces the time spent on re-rendering each computation.
why do we need this hook?🤔
So the answer is😊, in larger applications, we need lesser reaction time or rendering time
, and we also need to avoid re-renders, so the application won’t get slow🤫. If we had a small application example, so rendering time issues are difficult to find, but in large applications rendering time or response time actually becomes a large factor.
Example of useMemo
Now let's make a simple application 😜to demonstrate the use of the useMemo hook
.
This program has the following components:
- Increment button: starts from 0 and increases the count by 1
- Even num button: starts from 2 and returns even numbers going forward
- Also an evenNumDoouble() function which will return the twice value of the even number
we will create this through the useState
hook below:👇
import React, {useState} from 'react';
function Counter() {
const [count, setCount] = useState(0);
const [evenNum,setEvenNum] = useState(2)
function evenNumDouble(){
console.log("double");
return evenNum * 2;
}
return (
<div>
<h3>Counter: {count}</h3>
<h3>Even Numbers: {evenNum}</h3>
<h3>even Number Double Value: {evenNumDouble()}</h3>
<button onClick={() =>setCount(count+1)}>Increment</button>
<button onClick={()=>setEvenNum(evenNum+2)}>Even Numbers</button>
</div>
)
}
export default Counter;
In the above code we will find out the below points:
- When we click the button
'Even Numbers'
then the functionevenNumDouble()
is called since the state of'evenNum'
is changed But clicking the button 'Increment' also renders the
evenNumDouble()
function although the 'count' state is not changing This means that every time theevenNumDouble()
function is rendered unnecessarily on the page which reflects a less efficient code.This is the initial state of our app .
- Now see here only clicking on the increment button the
evenNumDouble()
function renders.
we will fix this through the useMemo
hook below:👇
import React,{useState, useMemo} from 'react'
function Counter() {
const [count, setCount] = useState(0);
const [evenNum,setEvenNum] = useState(2)
const memoHook = useMemo (function evenNumDouble(){
console.log("double");
return evenNum * 2;
},[evenNum])
return (
<div>
<h3>Counter: {count}</h3>
<h3>Even Numbers: {evenNum}</h3>
<h3>even Number Double Value: {memoHook}</h3>
<button onClick={() =>setCount(count+1)}>Increment</button>
<button onClick={()=>setEvenNum(evenNum+2)}>Even Numbers</button>
</div>
)
}
export default Counter
In the above code🕵️♀️,
we have set the output of
evenNumDouble()
function into a constantmemoHook
which will filter the function through theuseMemo hook
to check only if the specified variable (which is evenNum in this case) has changed then this function will be rendered otherwise not.Notice that the changing
state variable
is specified in square brackets at the end of useMemo hook similar to the useEffect hook.
- Now, if we run the above code then we will find out that our code runs the
evenNumDouble()
function only as required and not unnecessarily.
In the same manner, if you have a large code base
and your application is running slow then you can check whether there are any unnecessary renders on the page and restrict them using the useMemo hook
, this definitely speeds up your app and makes it more efficient😃.
That's all for today.
Happy coding...🤗