The primary purpose of useMemo hook is "performance optimization".
It returns a memoized value,
It accepts two arguments - create function (which should return a value to be memoized) and dependency array. It will recompute the memoized value only when one of the dependencies has changed.
Using useMemo you achieve:
referential equality of the values (to further send them to props of the components to potentially avoid re-renders)
eliminate redoing of the computationally expensive operations for same parameters
For example:
function App() {
const [data, setData] = useState([....]);
function format() {
console.log('formatting....'); // this will print only when data has changed
const formattedData = [];
data.forEach(item => {
const newItem = //...do soemthing here,
if (newItem) {
formattedData.push(newItem);
}
})
return formattedData;
}
const formattedData = useMemo(format, [data])
return (
<>
{formattedData.map(item => (
<div key={item.id}>
{item.title}
</div>
))}
</>
)
}