This project demonstrates how to use the useMemo hook in React to optimize expensive calculations and avoid unnecessary re-renders.
useMemois a React Hook that memoizes the result of a computation, so it’s only recalculated when its dependencies change.- Purpose: Prevents expensive calculations from running on every render if the input hasn't changed.
- Syntax:
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
- When you have a costly computation in your component that should only re-run when specific inputs change.
- When passing objects or functions as props to child components, to avoid unnecessary re-renders.
The following component calculates the factorial of a number. The calculation is intentionally expensive to demonstrate the benefit of useMemo.
import React, { useState, useMemo } from "react";
// Expensive factorial calculation
function factorial(n) {
console.log("Calculating factorial...");
if (n <= 0) return 1;
return n * factorial(n - 1);
}
function FactorialCalculator() {
const [number, setNumber] = useState(5);
const [otherState, setOtherState] = useState(false);
// Memoize the factorial calculation
const fact = useMemo(() => factorial(number), [number]);
return (
<div>
<h2>Factorial Calculator</h2>
<input
type="number"
value={number}
onChange={e => setNumber(Number(e.target.value))}
/>
<p>Factorial: {fact}</p>
<button onClick={() => setOtherState(!otherState)}>
Toggle Other State
</button>
</div>
);
}
export default FactorialCalculator;- The factorial calculation only runs when the
numberchanges. - Updating unrelated state (like
otherState) does not trigger the expensive calculation again. - Check your browser’s developer console to see when the calculation is run.
- Clone this repository or copy the code into your React project.
- Import and use the
FactorialCalculatorcomponent in your app.
Learn more: