Sobes.tech
Middle

Name the reasons why a React component re-renders. Why does React focus on changes in reference rather than changes in value?

sobes.tech AI

Answer from AI

A React component re-renders in the following cases:

  • When the props passed to the component change.
  • When the component's state changes via setState or useState hooks.
  • When the context (using Context API) that the component subscribes to changes.
  • When the parent component re-renders and the child component is not optimized (for example, not using React.memo).

React relies on reference changes rather than deep value comparisons because:

  • Comparing references is a very fast operation (pointer comparison in memory), whereas deep object comparison can be costly in terms of time.
  • This allows React to efficiently determine whether an object has changed without recursive traversal.
  • This approach simplifies implementation and improves performance, especially when working with large and complex data structures.

Example:

const [user, setUser] = useState({ name: 'Alice' });

// If we update the state like this:
setUser({ name: 'Alice' }); // the reference will change, and the component will re-render

// If we change a field inside the object without changing the reference:
user.name = 'Bob';
// React will not notice the change unless setUser is called with a new object

Therefore, it is important to create new objects when updating the state so that React can track changes via reference.

Name the reasons why a React component re-renders… - sobes.tech