Memoization Hook: Memo()

This prevents unnecessary re-renders.

 

A child component will not be recreated if the props have not changed.

function Page() {
  const [name, setName] = useState('Taylor');
  const [age, setAge] = useState(42);
  return <Profile name={name} age={age} />;
}

const Profile = memo(function Profile({ name, age }) {
  // ...
});

 

Gotchyas

Don't  pass in an object and then destructure - just send in what you need.

React does a shallow comparison - so the properties might be the same but the instance is different. This would cause an unnecessary render.

 

// Bad implementation that passes in an object.

function Page() {
  const [name, setName] = useState('Taylor');
  const [age, setAge] = useState(42);

  const person = useMemo(
    () => ({ name, age }),
    [name, age]
  );

  return <Profile person={person} />;
}

const Profile = memo(function Profile({ person }) {
  // ...
});