How to greatly improve your React app performance

A review of common React performance pitfalls and how to avoid them

  1. Bad shouldComponentUpdate implementations and why PureComponent won’t save you.
  2. Changing the DOM too fast.
  3. Using events and callbacks without limitations.

Own your shouldComponentUpdate

The Problem

Simple shallow implementation: 'this.props.children !== nextProps.children', but it's always returning true
PureComponent component is still always returning true

Possible Solutions

  1. Running a deep comparison can be a long, heavy, slow process by itself, and the render function will not execute until the shouldComponentUpdate function finishes running.
    Performance may therefore deteriorate even further.
  2. It depends on the current implementation of React Elements, and may break in future versions.
shouldComponentUpdate-Children live example

Allow your components to scale up

The Problem

  1. Triggering “Layout” too much — when you can trigger Composite or Paint instead.
  2. Layout Thrashing — where you trigger unnecessary DOM recalculations by reading from the DOM right after you have written to it multiple times.
Naive Collapse component
Multiple Collapse starting to take a toll on the app
Change performance to 6x slowdown on Chrome

Possible Solutions

  1. We are changing height, which according to csstriggers.com is triggering a Layout recalculation. If we managed to change something like transform instead, that would only trigger Composite and should be much smoother, right?
    Indeed, that would perform better, but it would also leave a blank space under the Collapse, since we would then never be changing its height.
  2. Line 3 is a classic example of Layout Thrashing: We do a read from the DOM by this.contentEl.scrollHeight, and then a write to the DOM by setting this.containerEl.style.height. Multiply it by the number of Collapse components.
    Wouldn’t it be nice if we could group all the reads, perform them together, and after that do all the writes?
Grouping reading & writing on Collapse opening

Put your callbacks on a leash

The Problem

Possible Solution

Debounce the event

In Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store