Suppose you have a module that displays a listing of products, each one with its own label and cost. Moreover, you have a separate function that determines the collective price for all the items. This is an illustration of how to employ the useMemo hook to store the result of the total price calculation:
import React, { useMemo } from 'react';
function ItemList({ items }) {
const totalPrice = useMemo(() => {
console.log('Calculating total price...');
return items.reduce((acc, item) => acc + item.price, 0);
}, [items]);
return (
<div>
<ul>
{items.map((item) => (
<li key={item.name}>
{item.name}: {item.price}
</li>
))}
</ul>
<p>Total price: {totalPrice}</p>
</div>
);
}
The useMemo hook lets us set up a variable, entitled totalPrice, in this instance. The first piece of the hook is a function that works out the cost of all the items; the second part is an array of dependencies, meaning that React will recalculate the price any time the dependencies alter. In this instance, the only thing that the calculation is reliant on is the items prop.
The useMemo hook memorizes the result of the function, so if the items prop hasn't changed since the last render, React will take the previous result instead of running the function again. This can be helpful for complicated calculations that don't need to be re-run every time the render is executed. For example, if there is a large list of items, figuring out the total cost on every render could be time-consuming; memorizing the result can increase performance.
It is worth noting that useMemo is not a substitute for useEffect. useMemo should be used to store the outcome of a function, while useEffect should be used for completing side effects like obtaining data from an API.
Top comments (0)