Expensive? - useMemo
by Tomas Trescakยท Advanced React

Root Folder
Not Attempted
NameProgress
Introduction
Not Read
๐Ÿฐ Player
Not Read
Setup
Not Attempted
NameProgress
Software Installation
Not Read
Project Setup
Not Read
Running and Testing
Not Read
React and ReactDOM
Not Read
๐Ÿ’ก Assignment 1: Welcome Message
Not Attempted
Submissions
Not Read
React
Not Attempted
NameProgress
JSX and Components
Not Read
Props
Not Read
๐Ÿ‘พ Exercise: Props
Not Attempted
CSS Styles
Not Read
useState and Hooks
Not Read
๐Ÿ‘พ Exercise: useState
Not Attempted
Conditional Rendering
Not Read
Lists
Not Read
๐Ÿ‘พ Exercise: Lists
Not Attempted
Forms and Events
Not Read
๐Ÿ‘พ Exercise: Forms
Not Attempted
๐Ÿ’ก Assignment 2: Front End
Not Attempted
Pure Components - memo
Lifecycle - useEffect
Expensive? - useMemo
DOM Interactions - useRef
forwardRef
useImperativeHandle
๐Ÿ‘พ useImperativeHandle
Not Attempted
Context
useCallback
useId
useReducer
Infrastructure
Not Attempted
NameProgress
Database
Not Read
NextAuth and Github Authentication
Not Read
Prisma and ORM
Not Read
Project Setup
Not Read
Project Authentication
Not Read
APIs
Not Attempted
NameProgress
APIs
Not Read
APIs - Slides
Not Attempted
Rest APIs
Not Read
Rest APIs - Express.js
Not Read
ReastAPIs - Next.js
Not Read
Securing APIs
Not Read
Securing APIs - NextAuth
Not Read
tRPC
Not Attempted
NameProgress
tRPC
Not Read
tRPC - Routers
Not Read
tRPC - Server Rendering
Not Read
tRPC - Client Rendering
Not Read
Persisting Data
Not Read
Assignment 3: APIs
Not Read
0 / 300 XP

Lecture Transcript
If you prefer text to video, check out the transcript of the presentation above

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.

Consider the calculateFibonacci function, which uses recursion to compute the Fibonacci sequence. This process is computationally very expensive.

When trying to increment the value of count, the UI is very sluggish as on each re-render, the sequence is recalculated.

The problem occurs on this line executing on each render.

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.

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!

Description
All the extra information about this section

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

Discuss with Maggie
Use the power of generative AI to interact with course content

Discussion

0 comments
Loading editor ...
Remember to be polite and report any undesirable behaviour

Category

Empty

Labels

Discussion has no labels

1 participant

user avatar

Priority

Notifications

You're not receiving notifications from this thread.
Course Outline