0
0
Reactframework~5 mins

React.memo usage

Choose your learning style9 modes available
Introduction

React.memo helps your app run faster by remembering a component's output. It skips redoing work if the inputs (props) stay the same.

You have a component that shows the same data many times without changes.
You want to avoid slow updates when parent components change but child props stay the same.
You want to improve performance in lists where many items rarely change.
You want to prevent unnecessary re-rendering of pure functional components.
Syntax
React
const MemoizedComponent = React.memo(Component);
Wrap your functional component with React.memo to create a memoized version.
React.memo only checks props shallowly by default to decide if it should re-render.
Examples
This memoized component only re-renders if the name prop changes.
React
const Hello = React.memo(function Hello({ name }) {
  return <p>Hello, {name}!</p>;
});
Memoized arrow function component for a button that updates only if onClick or label changes.
React
const Button = React.memo(({ onClick, label }) => {
  return <button onClick={onClick}>{label}</button>;
});
Using a custom comparison function to control when to skip re-rendering.
React
const CustomCompare = React.memo(Component, (prevProps, nextProps) => {
  return prevProps.value !== nextProps.value;
});
Sample Program

This example shows a memoized CountDisplay component that only re-renders when the count changes. Typing in the input does not cause CountDisplay to re-render, improving performance.

React
import React, { useState } from 'react';

const CountDisplay = React.memo(({ count }) => {
  console.log('CountDisplay rendered');
  return <p>Count: {count}</p>;
});

export default function Counter() {
  const [count, setCount] = useState(0);
  const [text, setText] = useState('');

  return (
    <div>
      <CountDisplay count={count} />
      <button onClick={() => setCount(count + 1)}>Increase Count</button>
      <input
        type="text"
        value={text}
        onChange={e => setText(e.target.value)}
        placeholder="Type here"
        aria-label="Input text"
      />
    </div>
  );
}
OutputSuccess
Important Notes

React.memo only works with functional components.

It does a shallow comparison of props by default, so objects or arrays as props may need custom comparison.

Use React DevTools to see when components re-render to check if memoization helps.

Summary

React.memo remembers a component's output to skip unnecessary re-renders.

Use it to improve performance when props rarely change.

You can provide a custom function to control when to re-render.