DEV Community

Geetika Bajpai
Geetika Bajpai

Posted on

useMemo Hook

useMemo is a hook that allows you to memoize expensive calculations to avoid unnecessary re-computations on every render.

Explanation of the Code

This React component, MemoTutorial, demonstrates how to use the useMemo hook to optimize performance by memoizing the result of a function that computes the longest name from a list of comments fetched from an API. Let's break down the code step by step.

1. Imports:

Image description

  • axios is used to make HTTP requests.
  • useEffect, useState, and useMemo are hooks from React.

2. Component Definition:

Image description
The MemoTutorial function is the React component.

3. State Variables:

Image description

  • data: Holds the comments fetched from the API.
  • toggle: A boolean used to trigger re-renders.

4. Fetching Data:

Image description

  • useEffect is used to fetch data from the API when the component mounts.
  • The empty dependency array ([]) ensures this effect runs only once.

5. Finding the Longest Name:

Image description

  • This function iterates through the comments array to find and return the longest name.

6. Using useMemo:

Image description

  • useMemo memoizes the result of findLongestName(data).
  • The function findLongestName(data) is called only when toggle changes.
  • If toggle remains unchanged, the previously computed result is returned without recomputing.
7. Rendering the Component:

Image description

  • getLongestName is displayed in a div.
  • A button toggles the toggle state.
  • When toggle is true, "toggle" is displayed in an h1.

Why Use useMemo?

1. Performance Optimization:

  • It helps prevent expensive calculations from being performed on every render.
  • In this example, findLongestName can be computationally expensive if the list of comments is large.

2. Dependencies:

  • The result of the memoized function (findLongestName) is recalculated only when the specified dependencies ([toggle]) change.
  • If the dependencies do not change, React returns the memoized value from the previous render.

3. Example Context:

  • Here, useMemo ensures findLongestName(data) is only recalculated when toggle changes.
  • Even if the component re-renders due to changes in other state or props, the memoized result is reused, avoiding redundant computations.

Top comments (0)