DEV Community

Coder
Coder

Posted on • Updated on

How to use React memo

React is an open-source frontend library used to build reusable UI components for websites and applications. It is widely used to build single-page applications and dynamic user interfaces. React memo is a feature in React that lets developers optimize their React applications by memoizing the components that are expensive to render. In this guide, we will go through how to use React memo in your code and how it can help you improve your React application's performance.

What is React Memo?

React memoization is the process of storing and reusing the result of a function call that has already been executed. It is used to optimize performance and reduce the number of repeated function calls. React memo is a higher-order component (HOC) that does the memoization automatically. When you wrap a component with React memo, it will only re-render when its props or state change. If none of its dependencies change, React memo will reuse the previously calculated result and save the expensive rendering process.

When Should You Use React Memo?

React memo is especially useful when you need to optimize components that are expensive to render. These components may contain complex logic, data fetching, or heavy rendering. Without memoization, these components can slow down your application, increase the rendering time and consume valuable resources.

How to Use React Memo?

Using React memo is straightforward. Simply wrap the component you want to optimize with the memo HOC. Here is an example:

import React, { memo } from 'react';

const SomeComponent = memo((props) => {
  // do some heavy computation or rendering here
  return (
    <div>
      {/* some JSX here */}
    </div>
  );
});

export default SomeComponent;
Enter fullscreen mode Exit fullscreen mode

In this example, we import the memo HOC from React and use it to wrap our component function. The component function is then passed as an argument to the memo function, which returns a memoized version of the component.

The memoized component will only re-render if its props or state changes. If none of its dependencies change, it will reuse the previously calculated result.

Using Memo with Functional Components

React's functional components have become increasingly popular because they are easier to read, write, and test. With React memo, optimizing functional components is easy too. Here is an example:

import React, { memo } from 'react';

const TodoList = memo((props) => {
  const { todos } = props;
  return (
    <ul>
      {todos.map((todo) => (
        <li key={todo.id}>{todo.text}</li>
      ))}
    </ul>
  );
});

export default TodoList;
Enter fullscreen mode Exit fullscreen mode

In this example, we create a functional component called TodoList. It receives an array of todos as its only prop and returns an unordered list of todo items. We then use the memo HOC to memoize the TodoList component.

Now, every time the TodoList component is called with the same todo array, its previous output will be reused, saving computation time.

Skipping Re-rendering with React Memo

Sometimes in a React app, you may have a component that only affects the layout or only changes the styling of another component. If this is the case, then you may not want to re-render the component even if its props or state have changed.

To achieve this, you can use the React memo function with an optional areEqual function. The areEqual function is passed as the second argument to the memo function and is used to compare the previous and current props and state of the component. If the areEqual function returns true, React memo will skip the re-rendering process.

Here is an example:

import React, { memo } from 'react';

const SomeComponent = memo((props) => {
  // do some rendering here
  return (
    <div style={{ ...props.style }} onClick={props.onClick}>
      {props.label}
    </div>
  );
}, (prevProps, nextProps) => {
  return (
    prevProps.style === nextProps.style &&
    prevProps.onClick === nextProps.onClick &&
    prevProps.label === nextProps.label
  );
});

export default SomeComponent;
Enter fullscreen mode Exit fullscreen mode

In this example, we created a SomeComponent that receives some props and renders a div element. We then passed a second parameter to memo, which is the areEqual function. The areEqual function compares the previous and current versions of the SomeComponent props passed when the component is re-rendered. The areEqual function effectively tells the component to only re-render if the style, onClick and label properties change.

Debugging with React Memo

React memo is an excellent tool for optimizing your app's performance, but it can also cause some bugs when used incorrectly. One of the most common bugs when using React memo is forgetting to pass a key prop to your memoized component.

Here is an example of what can happen:

import React, { memo } from 'react';

const TodoList = memo((props) => {
  // some logic here
  return (
    <ul>
      {props.todos.map((todo) => (
        <TodoItem data={todo} />
      ))}
    </ul>
  );
});

const TodoItem = memo((props) => {
  // some logic here
  return (
    <li>{props.data.text}</li>
  );
});

export default TodoList;
Enter fullscreen mode Exit fullscreen mode

In this example, we have a TodoList component that displays a list of todo items. We use the memo HOC to memoize the TodoList and TodoItem components. However, we forgot to pass a key prop to the TodoItem component, which can cause React to re-render the entire TodoList component every time a TodoItem is added or removed.

To fix this bug, we should add a key prop to the TodoItem component, like this:

import React, { memo } from 'react';

const TodoList = memo((props) => {
  // some logic here
  return (
    <ul>
      {props.todos.map((todo) => (
        <TodoItem data={todo} key={todo.id} />
      ))}
    </ul>
  );
});

const TodoItem = memo((props) => {
  // some logic here
  return (
    <li>{props.data.text}</li>
  );
});

export default TodoList;
Enter fullscreen mode Exit fullscreen mode

Adding the key prop to the TodoItem component can help React track the component instance and avoid re-rendering the TodoList component unnecessarily.

Conclusion

React memo is an excellent tool to optimize your app's performance by memoizing expensive components. The process of using memo is simple, and with its flexibility, you can optimize any part of your application. While you use the memo HOC, it is crucial to add a key prop to maintain the stability of your application. Knowing how and when to use memo is crucial for building scalable and performant React applications. You can now add memo to your toolkit to create faster and efficient React applications.

Top comments (0)