1. React.memo - Skip Child Re-renders

Problem

function Parent() {
  const [count, setCount] = useState(0);
  return (
    <div>
      <Child name="Rohit" />  {/* Re-renders every time! */}
      <button onClick={() => setCount(count + 1)}>Click: {count}</button>
    </div>
  );
}

Issue: Child re-renders when Parent re-renders, even though name prop never changes.

Solution

const Child = React.memo(function Child({ name }) {
  return <h2>Hello {name}</h2>;
});

Result: Child only re-renders when name prop actually changes.

How It Works

React.memo compares old props with new props using ===:

The Gotcha - Objects Break It

const Child = React.memo(function Child({ user }) {
  return <h2>Hello {user.name}</h2>;
});

function Parent() {
  const [count, setCount] = useState(0);
  return (
    <div>
      <Child user={{ name: "Rohit" }} />  {/* NEW object every render! */}
      <button onClick={() => setCount(count + 1)}>Click</button>
    </div>
  );
}

Problem: { name: "Rohit" } creates new object every render.

{} === {}  // false (different memory addresses)

React.memo sees "different" object → Child re-renders every time.

This is where useMemo comes in.


2. useMemo - Cache Values & Keep Same Reference