DEV Community

Chintan Soni
Chintan Soni

Posted on

Using React.memo to optimize your React applications

React.memo is a higher-order component (HOC) that can be used to wrap a component and memoize its rendered output. This means that React will only re-render the component if its props change. This can be useful for preventing unnecessary re-renders and improving the performance of your application.

When to use React.memo

React.memo should be used for components that:

  • Are pure components, meaning that they always return the same output for the same props and state.
  • Are frequently re-rendered, even when their props haven't changed.
  • Have expensive rendering logic.

How to use React.memo

To use React.memo, simply wrap your component in the React.memo() HOC. The React.memo() function takes a single argument, which is the component to be memoized. It returns a new memoized component, which can then be rendered in your application.

For example, the following code shows how to use React.memo to memoize a pure component:

import React, { memo } from "react";

const MyMemoizedComponent = memo(() => {
  return <div>Hello, world!</div>;
});

export default MyMemoizedComponent;
Enter fullscreen mode Exit fullscreen mode

Now, whenever the MyMemoizedComponent component is rendered, React will check if the props have changed. If the props haven't changed, React will reuse the memoized output from the previous render. Otherwise, React will re-render the component and generate a new memoized output.

Example usage

The following example shows how to use React.memo to optimize a list of items that is frequently re-rendered:

import React, { useState, memo } from "react";

const MyList = memo(({ items }) => {
  return (
    <ul>
      {items.map((item) => (
        <li key={item.id}>{item.name}</li>
      ))}
    </ul>
  );
});

export default function App() {
  const [items, setItems] = useState([
    { id: 1, name: "Item 1" },
    { id: 2, name: "Item 2" },
    { id: 3, name: "Item 3" },
  ]);

  return (
    <div>
      <MyList items={items} />
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

In this example, the MyList component is memoized, so it will only re-render if the items prop changes. This can lead to significant performance improvements, especially if the MyList component is rendered frequently.

Tips for using React.memo

Here are a few tips for using React.memo effectively:

  • Only use React.memo for pure components.
  • Be careful when memoizing components that use props as callbacks. Make sure that the same callback function instance is provided between renders.
  • Use profiling to measure the performance gains of memoizing a component.

Top comments (0)