useMemo
returns a memorized value, primary purpose of this hook is to optimize performance. It remembers the results of output for a given set of inputs.React re-renders the component and entire child component hierarchy when an update is made and when this re-rendering involves some heavy computation, it may degrade the performance and poor user experience.
Expensive operation could be anything like:
import React, { useMemo, useState } from "react";
const UseMemoHook = () => {
const [productList, setProductList] = useState();
const [productCount, setProductCount] = useState(1);
const clickHandler = () => {
//Time/resource consuming operation
formatData(getData());
};
const getData = () => {
fetch(`https://fakestoreapi.com/products?limit=${productCount}`)
.then((res) => res.json())
.then((json) => json)
.then((res) => {
//Resolving response
return res
});
};
const formatData = useMemo((data)=>{
//Expensive format operation
setProductList=[...expensiveOperation()];
}, [productCount]);
return (
<>
<button onClick={clickHandler}>Get Products</button>
<div>
Get product info<input
type="text"
value={productCount}
onChange={(e) => setProductCount(e.target.value)}
/>
</div>
{productList && productList.map((res) => {
return (
<div key={res.id}>
<span>{res.id}</span> <span>{res.title}</span>
<span>{res.price}</span>
<span>{res.category}</span>
<span>{res.description}</span>
<span>{res.image}</span>
</div>
);
})}
</>
);
};
export default UseMemoHook;
useMemo
hook is similar to useCallback
but it has a function that returns a value while useCallback
returns a memoized function.