Slide 1
-----------
Part 1: Let's take a look at how we can speed up component rendering when performing expensive computations.
Slide 2
-----------
Part 1: The useMemo hook in React is used to optimize performance by memoizing expensive computations. It prevents recalculating values unnecessarily by caching the result of a function when its dependencies don’t change.
Part 2: Consider the calculateFibonacci function, which uses recursion to compute the Fibonacci sequence. This process is computationally very expensive.
Part 3: When trying to increment the value of count, the UI is very sluggish as on each re-render, the sequence is recalculated.
Part 4: The problem occurs on this line executing on each render.
Part 5: Instead, we can use the useMemo hook, which will cache the result of the computation of the Fibonacci sequence. Similarly to useEffect hook, it has a dependency array that tells the useMemo when it needs to be re-computed.
Part 6: Try clicking on the Increment Count button to see that the response is much faster! Clicking on Change Input re-calculates the Fibonacci sequence, be patient!
UNDERSTANDING <STRONG>USEMEMO</STRONG> IN REACT
The useMemo hook in React is used to optimize performance by memoizing expensive
computations. It prevents recalculating values unnecessarily by caching the
result of a function when its dependencies don’t change.
--------------------------------------------------------------------------------
WHY <STRONG>USEMEMO</STRONG>?
In React, re-rendering components can trigger unnecessary recalculations.
useMemo ensures that the computation happens only when needed (i.e., when
specified dependencies change).
--------------------------------------------------------------------------------
CUSTOM HOOK EXAMPLE: <STRONG>USEEXPENSIVECALCULATION</STRONG>
Here’s a custom hook that demonstrates using useMemo to optimize an expensive
calculation.
CUSTOM HOOK CODE:
import { useMemo } from "react";
// Custom Hook: Optimizes an expensive computation
const useExpensiveCalculation = (number) => {
const calculate = (num) => {
console.log("Running expensive calculation...");
let result = 0;
for (let i = 0; i <= 100000000; i++) {
result += num + i;
}
return result;
};
const result = useMemo(() => calculate(number), [number]);
return result;
};
export default useExpensiveCalculation;
--------------------------------------------------------------------------------
HOW IT WORKS:
1. <strong>useMemo</strong> Cache:
* The expensive calculate function runs only if <strong>number</strong>
changes.
* If number remains the same, React uses the cached result.
--------------------------------------------------------------------------------
USAGE EXAMPLE
Here’s a component that uses the custom useExpensiveCalculation hook:
import React, { useState } from "react";
import useExpensiveCalculation from "./useExpensiveCalculation";
const ExpensiveCalculationDemo = () => {
const [number, setNumber] = useState(1);
const [increment, setIncrement] = useState(0);
const result = useExpensiveCalculation(number);
return (
<div>
<h1>useMemo Hook Example</h1>
<p>Result of Expensive Calculation: {result}</p>
<button onClick={() => setNumber(number + 1)}>
Change Input (Number: {number})
</button>
{/* Increment unrelated to expensive calculation */}
<button onClick={() => setIncrement(increment + 1)}>
Increment Count: {increment}
</button>
</div>
);
};
export default ExpensiveCalculationDemo;
--------------------------------------------------------------------------------
WHAT HAPPENS HERE?
* The expensive calculation (useExpensiveCalculation) only runs when number
changes.
* Clicking "Increment Count" triggers a re-render but does not recalculate the
expensive value because numberremains unchanged.
--------------------------------------------------------------------------------
KEY NOTES ABOUT <STRONG>USEMEMO</STRONG>:
* Syntax: useMemo(() => computation, [dependencies])
* Only recomputes the value if the dependencies change.
* Ideal for expensive calculations or derived data.
--------------------------------------------------------------------------------
This example demonstrates how useMemo can optimize performance in functional
components, making your React apps more efficient. Let us know if you'd like
more details or use cases! 🚀
Maggie is a generative AI that can help you understand the course content better. You can ask her questions about the lecture, and she will try to answer them. You can also see the questions asked by other students and her responses.
Join the discussion to ask questions, share your thoughts, and discuss with other learners