Select Page

Use of useMemo – Hook | React

Ashish Kumar
Published: June 28, 2022

Hello,

In this post, we will learn the use of useMemo Hook in React JS.

The purpose of useMemo hook is to memoize the output of a function, It means that it executes some function and remembers the output of that function. The useMemo hook is used to improve performance in our React application.

Syntax :

const memoizedValue = useMemo(functionThatReturnsValue, arrayDepencies)

The React useMemo hook accepts two parameters. These parameters are some functions whose output you want to memorize and an array of dependencies. 

The important part comes when your component re-renders. After re-render, any function in the component would be normally created. If you are also calling the function, it would be also executed again.

The useMemo hook helps you avoid this. It allows you to execute the memoized function only under specific conditions. When these conditions are not met, the useMemo will not execute the function. Instead, it will return the value from the last execution.

Let’s take a small example to understand

We have a component that does two things – Square a number and Increases the counter.

import React, { useState, useMemo } from "react";
const index = () => {
  const [number, setNumber] = useState(0);
  // Using useMemo
  const squaredNum = useMemo(() => {
    return squareNum(number);
  }, [number]);
  
  const [counter, setCounter] = useState(0);
  // Change the state to the input
  const onChangeHandler = (e) => {
    setNumber(e.target.value);
  };
  // Increases the counter by 1
  const counterHander = () => {
    setCounter(counter + 1);
  };
  return (
    <>
      <div className="App">
        <h1>UseMemo- Hook</h1>
        <input
          type="number"
          placeholder="Enter a number"
          value={number}
          onChange={onChangeHandler}
        ></input>
        <div>OUTPUT: {squaredNum}</div>
        <button onClick={counterHander}>Counter ++</button>
        <div>Counter : {counter}</div>
      </div>
    </>
  );
  // function to square the value
    function squareNum(number) {
        console.log("Squaring will be done!");
        return Math.pow(number, 2);
    }
};

export default index;

In the above example, useMemo runs only after the initial render. Here the function that returns the value i.e squareNum is passed inside the useMemo and inside the array dependencies, we have used the number as the squareNum will run only when the number changes.

If we increase the counter and the number remains the same in the input field the squareNum doesn’t run again.

Let’s see the output below.

Screenshot-from-2022-06-28-15-31-42

This is a small example to understand the useMemo Hook in React.

Check out our blog How to Create Next App

Happy Coding !!

Source: webkul.com