loading

React Memo


Using memo causes React to skip rendering a component if its props have not updated.

This can boost performance.

This section utilizes React Hooks. Hooks are discussed in further detail in the React Hooks section.


Problem

In this example, the Todos component re-renders even though the todos have not changed.

Example:

index.js:

-------- Example MUKAVU ------

Todos.js:

				
					const Todos = ({ todos }) => {
  console.log("child render");
  return (
    <>
      <h2>My Todos</h2>
      {todos.map((todo, index) => {
        return <p key={index}>{todo}</p>;
      })}
    </>
  );
};

export default Todos;
				
			

When you click the increment button, the Todos component reloads.

If this component was complex, it may lead to performance concerns.

Solution

To address this, we can use memo.

Use memo to prevent the Todos component from repeatedly re-rendering.

Wrap the Todos component export with a memo.

Example

index.js:

------- Example MUKAVU -------

Todos.js:

				
					import { memo } from "react";

const Todos = ({ todos }) => {
  console.log("child render");
  return (
    <>
      <h2>My Todos</h2>
      {todos.map((todo, index) => {
        return <p key={index}>{todo}</p>;
      })}
    </>
  );
};

export default memo(Todos);
				
			

Now, the Todos component only re-renders when the todos supplied to it via props change.

Share this Doc

React Memo

Or copy link

Explore Topic