REACT Tutorial



REACT MEMO


React Memo

React.memo is a higher-order component that helps to prevent unnecessary re-renders of functional components by memoizing the result. It’s a powerful optimization tool that improves performance, especially in large-scale React apps.

When a component receives the same props again, React.memo prevents it from re-rendering. This is useful in components that render frequently or have expensive rendering logic.

Basic Syntax

const MyComponent = React.memo(function MyComponent(props) {
  return <div>{props.name}</div>;
});

When Should You Use React.memo?

  • Your component renders the same output given the same props.
  • The component is rendered frequently, and performance is affected.
  • You're passing down large or complex data structures via props.

Example with and without React.memo

Without memoization, even unchanged props will re-trigger rendering:

function User({ name }) {
  console.log("Rendering User");
  return <p>Hello, {name}</p>;
}

function App() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <User name="Rahul" />
      <button onClick={() => setCount(count + 1)}>Click</button>
    </div>
  );
}

Using React.memo, User component won't re-render unless its props change:

const User = React.memo(function User({ name }) {
  console.log("Rendering User");
  return <p>Hello, {name}</p>;
});
Important Notes:
  • React.memo only works for functional components.
  • It performs a shallow comparison of props by default.
  • You can customize comparison with a second argument.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review