Sobes.tech
Middle+

How does React compare props? How does shallow comparison work?

sobes.tech AI

Answer from AI

React compares new props with previous ones when updating a component to determine if it needs to re-render. In most cases, React uses shallow comparison for props.

Shallow comparison means React compares only the top-level values of props using the strict equality operator (===). If the props are primitives (numbers, strings, booleans), the comparison is straightforward. If a prop is an object or array, the comparison is based on the reference to the object, not its contents.

For example, if a prop is an object with the same keys and values, but it's a new object (a new reference), React will consider the props changed, and the component will re-render.

This is important to consider when optimizing components, for example, when using React.memo or shouldComponentUpdate. To avoid unnecessary re-renders, you should pass immutable objects or memoize props.

How does React compare props? How does shallow… - sobes.tech