For more tips like this, sign up to the weekly newsletter!

Use class methods as functions with React.PureComponent

React.PureComponent is an optimized component that skips rerenders if its props and state did not change. Using that can boost the speed of a setState call, as entire subtrees can be skipped.

But with an inline function declaration, like func={() => {...}}, this advantage is nullified.

Inline vs. class method functions

The following component uses a function declared inline:

render() {
  return <PureElement func={() => {}}/>
}

While this one uses a class method and passes it unmodified:

onCall() {
}
render() {
  return <PureElement func={this.onCall}/>
}

From a functional point of view, there is no difference. Both pass down a function as a prop.

But for the child element, they are far from being the same.

Change checking

The inline function creates a new function every time render is called, while the class method is created once and gets reused.

When the child checks whether the props are changed, it uses a referential equality check for functions (===). Due to the functions' closures, there is no better way to make sure they are the same.

For the class method, this.props.func === nextProps.func, but for the inline declarations, they will be different.

So React.PureComponent has no other choice but to rerender the component every time.

To benefit from the performance optimizations React.PureComponent brings, avoid declaring functions inline.

Try it
References
Learn more: