Blog>
Snippets

Performance Optimization with `React.memo`

Showcase a component wrapped with `React.memo` to avoid unnecessary re-renders when props have not changed.
import React from 'react';

// A functional component that we will wrap with React.memo
const MyComponent = ({ text }) => {
  console.log('MyComponent renders'); // For demonstration purposes
  return <div>{text}</div>;
};

// Wrapping MyComponent with React.memo
// This will prevent re-renders if props did not change
const MemoizedMyComponent = React.memo(MyComponent);

export default MemoizedMyComponent;
This piece of code declares a React functional component 'MyComponent' which receives a 'text' prop and renders it within a div. 'MyComponent' is then wrapped with 'React.memo' which creates a memoized version of the component called 'MemoizedMyComponent'. This memoized component will avoid unnecessary re-renders if the 'text' prop does not change, leading to better performance.