What is useMemo hook in React..

nasreenkhalid

NasreenKhalid

Posted on October 5, 2021

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...

💖 💪 🙅 🚩
nasreenkhalid
NasreenKhalid

Posted on October 5, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related