Skip to main content

how to avoid unnecessary renders using react memo

ยท 2 min read
Parth Maheta

React.memo is a higher-order component in React that's used for optimizing functional components by preventing unnecessary re-renders. It's similar in purpose to the shouldComponentUpdate lifecycle method in class components. When you wrap a functional component with React.memo, it will only re-render if its props have changed.

Here's a simple example to illustrate the use of React.memo:

import React, { useState } from 'react';

// Regular functional component
const ChildComponent = ({ name }) => {
console.log('ChildComponent rendered');
return <p>{name}</p>;
};

// Wrap the functional component with React.memo
const MemoizedChildComponent = React.memo(ChildComponent);

const ParentComponent = () => {
const [count, setCount] = useState(0);

const incrementCount = () => {
setCount(prevCount => prevCount + 1);
};

return (
<div>
<button onClick={incrementCount}>Increment Count</button>
{/* Only MemoizedChildComponent will re-render when its props change */}
<MemoizedChildComponent name={`Count: ${count}`} />
</div>
);
};

const App = () => {
return <ParentComponent />;
};

export default App;

In this example:

  1. ChildComponent is a simple functional component that takes a name prop and renders a paragraph element with the given name. It logs a message to the console when it renders.

  2. MemoizedChildComponent is created by wrapping ChildComponent with React.memo. This means that MemoizedChildComponent will only re-render if its props change.

  3. In the ParentComponent, there's a button that increments the count state. The MemoizedChildComponent receives a prop with the current count, and it will only re-render when the count changes.

  4. If you open the browser's console and click the "Increment Count" button, you'll notice that ChildComponent is not re-rendering on each click, thanks to React.memo.

React.memo is a helpful tool for optimizing functional components, especially when dealing with components that have expensive rendering logic or when you want to avoid unnecessary re-renders in your application. Keep in mind that React.memo does a shallow comparison of props, so it works well when props are simple values or references that don't change often. If your props contain complex objects or functions, you might need to use other techniques for more fine-grained control over when a component should re-render.