Open In App

React JS useMemo Hook

Improve
Improve
Like Article
Like
Save
Share
Report

The useMemo is a hook used in the functional component of react that returns a memoized value. Memoization is a concept used in general when we don’t need to recompute the function with a given argument for the next time as it returns the cached result. A memoized function remembers the results of output for a given set of inputs. In React also, we use this concept, whenever in the React component, the state and props do not change the component and the component does not re-render, it shows the same output. The useMemo hook is used to improve performance in our React application.

Prerequisites:

React JS useMemo Hook:

In React useMemo Hook returns a memoized value and prevents the application from unnecessary re-renders. It is useful in heavy computations and processes when using functional components.

Syntax:

const memoizedValue = useMemo(functionThatReturnsValue, arrayDependencies)

Example: This example demonstrates when not to use the useMemo Hook.

Javascript




// Filename - App.js
 
import React, { useState } from "react";
 
function App() {
    const [number, setNumber] = useState(0);
    const squaredNum = squareNum(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>Welcome to Geeksforgeeks</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 App;


Output: In the above example, we have an App component and this component is doing two things one is squaring a number on the given input and incrementing the counter. We have two states here number and counter, whenever any of the states change the component re-renders. For example, if we change the input value of the number the function squareNum runs, and if increment the counter again the function squareNum runs. We can see this on the console. 

In this case, we can see that even if we changed the input number once, but clicked on-increment counter multiple times our function squareNum got executed whenever we clicked the increment counter button multiple times. This is happening because the App component re-renders whenever we change the state of the counter.

Now let’s solve this problem using the useMemo hook.

Example: This example demonstrates when to use useMemo Hook.

Javascript




// Filename - App.js
 
import React, { useState } from "react";
 
function App() {
    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>Welcome to Geeksforgeeks</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 App;


Output: Now in the above example, we have used the user memo hook, 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.

Now we can see in the console that the squareNum is running only when there is a change in the input box and not when the button of the increment counter is clicked.

Note: Memorization is never free, we are trading space for time. 



Last Updated : 28 Nov, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads