DEV Community

Cover image for What is useMemo hook in React..
NasreenKhalid
NasreenKhalid

Posted on

What is useMemo hook in React..

Hooks are relatively new feature of react, they were introduced in React 16.8, they help us make use of state and react features from a function based component, for example useState, useEffect, useHistory and many others. Hooks help us to avoid the complexities of classes and make our code simpler to read and understand.
In this article, we will go about the useMemo hook in React. In addition to understanding the functionality of this hook, it is also important to note that this hook has its importance from react interview perspective since many interviewers like to ask questions related to useMemo hook.

Now let's start learning the useMemo hook:

From the definition point of view, useMemo is a hook that is used in the functional component of React that returns a memoized value, for details read here
The basic purpose of useMemo hook is related to the fact that we try to avoid the unnecessary re-rendering of components and props in our program, so we make sure that only those components are re-rendered which witness a change in their values otherwise no need to re-render the component and slow down the performance, this will make your program efficient and improves the overall performance of your React app.
Now let's make a simple application to demonstrate the use of useMemo hook. This program has the following components:

  • Increment button: starts from 0 and increase 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
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;


Enter fullscreen mode Exit fullscreen mode

In the above code we will find out the below points:

  • When we click the button 'Even Numbers' then the function evenNumDouble() 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 the evenNumDouble() function is rendered unnecessarily on the page which reflects a less efficient code, 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

Enter fullscreen mode Exit fullscreen mode

In the above code, we have set the output of evenNumDouble() function into a constant memoHook which will filter the function through the useMemo 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...

Discussion (10)

Collapse
seankimdev profile image
Sean Kim • Edited on

Thank you for the awesome explanation! I’m excited to try this hook. I have a question though. Can you elaborate on why clicking the increment button rerenders the function although the count state is not changing as you stared below?

“But clicking the button 'Increment' also renders the evenNumDouble() function although the 'count' state is not changing”

Collapse
nasreenkhalid profile image
NasreenKhalid Author

When we click 'increment' button, the whole page is re-rendered therefore it executes every function without keeping in mind that clicking 'increment' button has no effect on 'evenNum' state and to restrict this unnecessary re-render we have used useMemo hook.

Collapse
seankimdev profile image
Sean Kim

Why does it rerender the entire page? Is it because it’s in the same component?

Thread Thread
nasreenkhalid profile image
NasreenKhalid Author

yes that's correct

Thread Thread
seankimdev profile image
Sean Kim

Got it. Thank you so much! :)

Thread Thread
nasreenkhalid profile image
NasreenKhalid Author

Pleasure :)

Collapse
ihtesham_haider profile image
Ihtesham Haider

I will definitely use!! Hooks thanks man!/women!

Collapse
nasreenkhalid profile image
NasreenKhalid Author

Thanks for your comment :)

Collapse
sergiycheck profile image
Serhii

Nice and short explanation. By the way, I was asked about useMemo hook on the last interview that I didn't passed :)

Collapse
nasreenkhalid profile image
NasreenKhalid Author

Thanks and all the best :)