Middle
What is useMemo used for? Provide a practical example.
sobes.tech AI
Answer from AI
useMemo is used in React to memoize computed values to avoid expensive recalculations on every component render.
Example: suppose you have a component that calculates the sum of a large array of numbers. Without useMemo, this operation would be performed on every render, even if the array hasn't changed.
import React, { useMemo } from 'react';
function SumComponent({ numbers }) {
const total = useMemo(() => {
console.log('Calculating sum');
return numbers.reduce((acc, num) => acc + num, 0);
}, [numbers]);
return <div>Sum: {total}</div>;
}
Here, the sum will only be recalculated when the numbers array changes. This improves performance, especially with complex calculations.