React useMemo Hook
React useMemo
'useMemo' is a React Hook that memoizes the result of a computation.
It's particularly useful for optimizing performance when dealing with expensive calculations or computations that don't need to be recalculated on every render.
Here's a basic example of how to use 'useMemo':
import React, { useState, useMemo } from 'react';
const MyComponent = () => {
const [a, setA] = useState(0);
const [b, setB] = useState(0);
// Expensive computation
const expensiveComputation = () => {
console.log("Running expensive computation...");
return a * b;
};
// Memoized result using useMemo
const result = useMemo(() => expensiveComputation(), [a, b]);
return (
<div>
<p>Result: {result}</p>
<input type="number" value={a} onChange={(e) => setA(Number(e.target.value))} />
<input type="number" value={b} onChange={(e) => setB(Number(e.target.value))} />
</div>
);
};
export default MyComponent;
In this example: