Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
useMemo Hook | React Hooks and Context
React Mastery
course content

Contenido del Curso

React Mastery

React Mastery

1. Introduction to React Fundamentals
2. Styling in React Apps
3. React Hooks and Context
4. React in the Real World

bookuseMemo Hook

The useMemo hook enables us to memoize the result of a function, optimizing expensive computations by caching the result. It is advantageous when we have frequent and resource-intensive calculations that yield the same result when the data doesn't change. This eliminates the need for redundant recalculations, resulting in improved performance.

Syntax:

We declare a new variable, such as cachedValue, and assign it to the useMemo hook. Inside the hook's parentheses, we provide a function (e.g., calculateValue), which will be executed to compute the memoized value. This function can be any valid JavaScript function. Additionally, we include a second argument—an array called dependencies —that consists of the values on which the memoized value relies.

When any dependencies specified in the dependencies array change, the memoized value will be recomputed. However, if the dependencies remain the same between renders, React will return the previously computed value without recomputation.

Note

This optimization helps improve performance by avoiding unnecessary calculations and results in a more efficient user experience.

Example 1

Let's create the ShoppingCart component, which will store the information about the number of products the user selects. Additionally, it will handle the logic for calculating the total sum, indicating the amount the user has to pay. Our primary objective is to memoize the total sum and recalculate it only when the user modifies the products prop passed to this component.

The calculation of the totalPrice is performed within the useMemo hook, which prevents unnecessary recalculation on each re-render of the component.

Line by line explanation:

  • Line 1: We import the useMemo hook from the React library to leverage its functionality;
  • Line 3: The ShoppingCart component is defined using the conventional function syntax;
  • Line 4-10: We create the totalPrice variable responsible for the total price the user has to pay. The useMemo hook is used for not performing calculations on each render;
    • Line 5-9: Within the arrow function passed to useMemo, the logic for calculating the total sum is implemented. Each item in the products array is iterated, and the price is multiplied by the quantity and added to the sum variable;
    • Line 10: The dependency array [products] is provided to the useMemo hook. This indicates that the memoized value should be recalculated if the products array changes.
  • Lines 12-31: The component's markup is rendered.
    1. Line 16: The map method is used to render each product in the products array, creating a corresponding JSX element;
    2. Line 17: The key attribute is set to ensure efficient rendering of the array items and help React identify each item uniquely;
    3. Line 28: The value of the totalPrice variable is rendered within the JSX, displaying the calculated total price.

Full app code:

Note

It is advisable not to mix the useEffect and useMemo hooks to ensure clarity and avoid confusion. The key distinction lies in their respective purposes: useEffect is employed for managing side effects and component lifecycle, whereas useMemo memoizes costly computations to enhance performance.

1. What is the main purpose of the `useMemo` hook in React?
2. When does the `useMemo` hook recompute its memoized value?
What is the main purpose of the `useMemo` hook in React?

What is the main purpose of the useMemo hook in React?

Selecciona la respuesta correcta

When does the `useMemo` hook recompute its memoized value?

When does the useMemo hook recompute its memoized value?

Selecciona la respuesta correcta

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 3. Capítulo 8
some-alt