Avoiding Reconciliation

Even if reconciliation is fast, there are situations where you might want to manually bypass reconciliation completely for a component in order to eek out more performance.

Whenever a component's state changes, React re-renders the component and all of its children. Often times, the component and its children barely change yet we need to re-render everything. This seems inefficient, doesn't it?

Remember that React works with a virtual representation of the DOM, only interacting with the actual DOM when needed. If one render pass results in the same contents as the previous render, it is a no-op with respect to DOM interactions. If you want to take an even shorter shortcut, the component lifecycle hook shouldComponentUpdate lets you bypass rendering the virtual DOM completely.

class MyComponent extends React.Component {
  shouldComponentUpdate(nextProps, nextState) { 
    /* 
     * You can compare nextProps/nextState to this.props / this.state to determine
     * whether the component should re-render or not.
     * This function should return a boolean (whether the component should re-render)
     */
    return false; 
  }
}

Premature Optimization? You typically shouldn't need to use shouldComponentUpdate unless you notice performance issues and suspect over-aggresive rerendering as the culprit. Using shouldComponentUpdate adds code complexity and more surface area for bugs to appear, especially ones that are hard to debug.

There are two reasons why you may want to optimize with shouldComponentUpdate:

  • You have used profiler tools and it is telling you that there is significant wasted time rendering for nothing.

  • You are able to make strong guarantees about when a component can and cannot change.

In either of these case, you should likely consider using React.PureComponent over using shouldComponentUpdate manually.

Last updated