The Comparison Function Execution Cost
What you'll learn: Understand that React.memo's shallow equality checks consume CPU cycles on every render, even when they successfully prevent re-renders.
The Hidden Cost of Optimization
When you wrap a component with React.memo, you're essentially making a trade-off: you're asking React to do extra work (comparing props) in exchange for potentially skipping a re-render. But here's the catch: that comparison happens every single time the parent renders, regardless of whether the props actually changed.
The Comparison Runs Always
Think of it like a security guard checking your ID every time you enter a building. Even when you're a regular and nothing has changed, the guard still has to look at your ID, compare it to their records, and verify everything matches. That verification process takes time, even if it's just a second.
Similarly, React.memo performs a shallow equality check on every prop, comparing the old values to the new values using Object.is. For a component with three props, that's three comparisons. For a component with ten props, that's ten comparisons. This happens on every parent render.
When the Cost Matters
For most components with a handful of primitive props, this cost is negligible—fractions of a millisecond. But if you have:
- Components with many props
- Custom comparison functions doing complex logic
- Hundreds of memoized components in the tree
...the cumulative cost of all these comparison functions can actually exceed the cost of just re-rendering the components normally, especially if those re-renders are fast.
Key Takeaway: React.memo's comparison function runs on every render whether props changed or not, adding CPU overhead that must be justified by the cost of the re-renders it prevents.