Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

React useMemo Hook

In this part, we will learn about React useMemo hook. The React useMemo returns a memoized Value when the dependency array gets changed. The word ‘memoized’ or ‘memoization‘ is an optimization technique to speed up expensive function calls by returning cached results instead of re-computing. basically, it’s like cache memory which is used to speed up your browser, something like that.

React useMemo hook is basically used when we want to avoid function re-call again and again for particular value and when we need to speed up our application, hence it helps us to gain performance. You might be thinking, useMemo looks like useCallback hook, which is true. The only difference is useMemo returns the memoized value from the expensive function, and useCallback returns the memoized callback, or you can say function.

React useMemo Hook

Syntax

const memoizedValue = useMemo(functionThatReturnsValue(), 
                                   [arrayDepencies])

In React useMemo hook, we have to pass a function which returns a value and an array of dependencies. useMemo will return a memoized value that only changes when any dependencies gets changed, with this we prevent re-rendering expensive functions. This is pretty useful when we need optimization.

It is not necessary to pass something to an array of dependencies, you can also pass a blank array.

Note: The dependencies array is not passed as an argument to the function. Conceptually, that’s what they represent: every referenced value should be passed in the dependencies array.

Let’s understand the whole thing using an example,

Problem Without React useMemo

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 reactjsguru</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;

The problem is raised here without useMemo is, if we change some value, then all present states will get re-rendered. Instead of that, we want that, only those state should re-render which got affected by change in value others should be untouched. here we have two operations, one for squaring the number and other one to get power of the number. Whenever state changes, the component will be rendered, even when we change counter value then also component will be re-rendered which actually makes the application pretty slow and this problem we will face in larger applications.

Output

React useMemo

Okay, this will be the output we will get if we change the value of counter and state. You might not be getting it, so let me make it easy for you, initially we will have 0 in text field and counter to 0. And if you run the application then in console, we will get a message “squaring will be done” which we have passed using console.log, This means whenever the component renders then this message will be print in our console.

Now we have incremented the counter for 4 times, because of that message keep printing every time when we increment the counter, and this is what we have problem is. And obviously if we change the value in the text field, or you can say while changing state, then the component will get re-render.

Solution with React useMemo

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);

const onChangeHandler = (e) => {
	setNumber(e.target.value);
}
	
// Increases the counter by 1
const counterHander = () => {
	setCounter(counter + 1);
}
return (
	<div className="App">
	<h1>Welcome to reactjsguru</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

React useMemo

So as you can see, when we use useMemo hook, when we change state to 0123 then the message will print, this means component renders when we change state. Now when we try to change counter then the Component won’t be re-rendered.

You might have question raised that, why 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. We have here 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.

Reactjs Guru
Reactjs Guru

Welcome to React Guru, your ultimate destination for all things React.js! Whether you're a beginner taking your first steps or an experienced developer seeking advanced insights.

React tips & tutorials delivered to your inbox

Don't miss out on the latest insights, tutorials, and updates from the world of ReactJs! Our newsletter delivers valuable content directly to your inbox, keeping you informed and inspired.

Leave a Reply

Your email address will not be published. Required fields are marked *