React useMemo hook and use case.
useMemo
is a React Hook that lets you cache the result of a calculation between re-renders. React.useMemo are Used to optimize the performance of react application by memoizing the expensive calculation.
Let's take an example without using useMemo hook.
import React, { useMemo } from "react";
let ListItem = ({ data }) => {
let result = addSomeCal(data);
return <div>{result}</div>;
};
export default ListItem;
const addSomeCal = (data) => {
let res = 1;
for (let i = 0; i < data; i++) {
res += i * 4;
}
return res;
};
In this above example, if the parent component of ListItem will render ListItem component re-render every time data changes or not.
The problem in this example, “addSomeCal” method called every time with the same data props, which means calculating the same result again & again while re-rendering it’s affects the performance of the react app if data props have a larger value.
To Overcome this problem we should use React.useMemo hook.
import React, { useMemo } from "react";
let ListItem = ({ data }) => {
let result = useMemo(() => addSome(data), [data]);
return <div>{result}</div>;
};
export default ListItem;
const addSome = (data) => {
let res = 1;
for (let i = 0; i < data; i++) {
res += i * 4;
}
return res;
};
By using useMemo we can improve the performance of react app, The above shows how to use useMemo hook in your react app.
Parent or App component.
import React from "react";
import "./styles.css";
import ListItem from "./list.js";
export default function App() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<ListItem data={10000} />
</div>
);
}
When we should use useMemo: A component that uses any heavy Calculation that takes much time to calculate the result at a given certain “data”(large data set).
Demo code-sandbox
👉 How to handle re-render without changing props, component should be not render follow story
For more about useMemo follow React.official docs