useMemo is a memoization Technique to improve the Performace of your App.useMemo is a hook used in the functional component of react that returns a memoized value
What's Memoization?
Memoization is an optimization technique used primarily to speed yo the computer programs by storing the result of responsive function calls and returning the cached result when the same input occur again
In simple terms. A memoized function remembers the results of output for a given set of inputs and returned the result from cached memory instead of recalculating for the same input
syntax of useMemo()
const memoizedResult = useMemo(function, [...arrayDepencies])
During initial rendering, useMemo(function, [...arrayDepencies]) invoke the function, memoizes the calculated output, and returns it to the component.
If during the next renderings the arrayDepencies don’t change, then useMemo() doesn’t invoke function but returns the memoized value. If no array is provided, a new value will be computed on every render.
But if arrayDepencies change during re-rendering, then useMemo() invokes compute, memoizes the new value, and returns it.
Let me explain with an example
import { useState } from "react";
import "./styles.css";
export default function App() {
const [number, numberSetter] = useState(0);
const [isEven, isEvenSetter] = useState("false");
function square(n) {
console.log("square ran");
return n * n;
}
let factorialNumber = square(number)
function checkEven() {
isEvenSetter(factorialNumber % 2 === 0 ? true : false);
}
return (
<div className="App">
<div>
<input value={number} onChange={(e) => numberSetter(e.target.value)} />
<p>square : {factorialNumber}</p>
</div>
<button onClick={checkEven}>IsEven ?</button>
{isEven && <p>Square Is Even</p>}
</div>
);
}
Source to the unoptimized code codeSand
In the above cove as soon as we type a number in the inputBox we calculate the square via square function and it gets displayed on the screen
When we click on the IsEven Button it checks if the squared value is square or not if it is then it prints a message if not even it doesn't print a value
we are console.logging "square ran" every time square function ran;
as we can see above the square function ran twice once to calculate the square for the first time and then once when we check if the square is even because isEven State changes and the whole component re-rendered but we already had the squared value why should we re-calculate the square for same input value on every re-rendering? We shouldn't that's why we use the useMemo hook
Let's write the above code with the user memo hook
import { useState, useMemo } from "react";
import "./styles.css";
export default function App() {
const [number, numberSetter] = useState(0);
const [isEven, isEvenSetter] = useState("false");
function square(n) {
console.log("square ran");
return n * n;
}
let factorialNumber = useMemo(() => square(number), [number]);
function checkEven() {
isEvenSetter(factorialNumber % 2 === 0 ? true : false);
}
return (
<div className="App">
<div>
<input value={number} onChange={(e) => numberSetter(e.target.value)} />
<p>square : {factorialNumber}</p>
</div>
<button onClick={checkEven}>IsEven ?</button>
{isEven && <p>Square Is Even</p>}
</div>
);
}
Source to the optimized code codeSand
The output for this would be
However, if you click the isEven button, "square ran" isn’t logged to the console because useMemo() returns the memoized square calculation. i.e the function inside the user memo hook only run if the dependency we passed into it changes
conclusion
useMemo(() => function(a, b), [a, b]) is the hook that lets you memoize expensive function . if no value in the dependency array changes, once memoized, the hook is going to return the memoized value without invoking function(a, b).