Optimizing Your React App

React’s Diffing Algorithm

By default, a React app will re-render a DOM tree on every state change after comparing a previous virtual DOM tree to the current one. This sounds like an involved process, especially for large apps, but React’s diffing algorithm allows an app to render a different tree of React elements in O(n) time. This algorithm relies on the assumption that two elements of different types will produce different trees.

Optimizing with shouldComponentUpdate()

While React’s diffing algorithm is effective for the vast majority of practical use cases, its underlying assumption (i.e., that two elements of different types will produce different trees) may cause unnecessary re-renders, which can then result in performance issues for large, complex apps. To optimize the diffing algorithm, React provides a shouldComponentUpdate() hook.

The shouldComponentUpdate() method is one of React’s many “lifecycle methods” — functions that can be invoked at particular times in the component rendering (or removal) process. The shouldComponentUpdate() method, which is called right before a component would otherwise re-render, tells React whether the component’s output will be affected by the current state change. The shouldComponentUpdate() method returns true by default. But if it returns false, the component will not re-render, which in turn, speeds up the diffing process.

Profiling with Perf

React’s built-in Perf tool is designed to log performance data as you use your React app. As such, it can show you exactly where your app can be optimized, specifically, by invoking Perf’s printWasted() method.

The printWasted() method displays “wasted time,” which is the amount of time spent rendering components that haven’t changed. These are the components that can be targeted with the shouldComponentUpdate() hook. With shouldComponentUpdate() and Perf, React provides the necessary tools for squeezing that extra performance boost out of your React app.

For more information on Perf, see https://facebook.github.io/react/docs/perf.html

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.