Junior — Middle
In what case and why is React Hook useMemo used for component performance optimization?
sobes.tech AI
Answer from AI
React Hook useMemo is used for memoizing (caching) the result of computations to avoid re-executing expensive or time-consuming functions on every component render. This helps optimize performance, especially when the calculations depend on certain data and should not be recalculated unnecessarily.
For example, if you have a function that filters or sorts a large array, and you want it to run only when the input data changes, useMemo will store the result and reuse it on subsequent renders:
import React, { useMemo } from 'react';
function MyComponent({ items, filter }) {
const filteredItems = useMemo(() => {
return items.filter(item => item.includes(filter));
}, [items, filter]);
return (
<ul>
{filteredItems.map(item => <li key={item}>{item}</li>)}
</ul>
);
}
Here, useMemo ensures that the array filtering only occurs when items or filter change, not on every component render.