Q1. What is useMemo in React?
useMemo is a React Hook used to memorize the result of an expensive calculation. It prevents recalculating the value on every render unless its dependencies change.
*Syntax : *
const memoizedValue = useMemo(() => {
return calculation;
}, [dependencies]);
Q2. Why do we use useMemo?
We use useMemo to:
- Avoid unnecessary calculations.
- Improve application performance.
- Cache calculated values between renders.
Q3. What happens if we don't use useMemo?
The calculation executes again on every render, even when its dependencies haven't changed. This can affect performance when calculations are expensive.
Example: Multiply Two Numbers
import { useMemo, useState } from "react";
function App() {
const [number, setNumber] = useState(5);
const [count, setCount] = useState(0);
const result = useMemo(() => {
console.log("Calculating...");
return number * 10;
}, [number]);
return (
<>
<h2>Number: {number}</h2>
<h2>Result: {result}</h2>
<h2>Count: {count}</h2>
<button onClick={() => setNumber(number + 1)}>
Change Number
</button>
<button onClick={() => setCount(count + 1)}>
Increase Count
</button>
</>
);
}
export default App;
Output:
Number = 5
Result = 50
Count = 0
In this example, changing Count does not change the calculated result. In the React code, useMemo also avoids recalculating it when Number stays the same.
Top comments (0)