← React Beginner Questions - Set 3 Q25

What is React.memo?

React Beginner Questions - Set 3

A wrapper that re-uses the previous render when the props have not changed. It is a shallow comparison, and that detail decides whether it works.

Example

import { memo, useState } from 'react';

const Row = memo(function Row({ label }) {
  console.log('render', label);
  return <li>{label}</li>;
});

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

  return (
    <>
      <button onClick={() => setCount(c => c + 1)}>{count}</button>
      <Row label={text} />        {/* does not re-render */}
      <Row label={{ toString: () => text }} /> {/* new object each render -> always re-renders */}
    </>
  );
}

What to notice

← Back to the question list