How we improved our React/React Native project's performance by 250% with just a small tweak.

Varun Raj
Varun Raj, Co-founder and CTO
How we improved our React/React Native project's performance by 250% with just a small tweak.

The reason behind this is that whenever you component’s props changes, the framework re-renders it in the DOM with the new props. Even though React updates the DOM based on DIff mechanism there are cases when the child gets updated when the parent is updated.

Improve React be 250%

The Framework provides a lifecycle method that can help you avoid re-rendering of components in unwanted scenarios. The method shouldComponentUpdate is called whenever you update the state of the component.

class Greeting extends React.Component {
...
shouldComponentUpdate(nextProps, nextState) {
return boolean; //Either true or false
}
...
}

Based on the value it returns the framework depending upon whether to update the component and re-render or simply skip the re-rendering part.

A Common Scenario

A very common scenario of this case is when you have a common button component with two pros one is the button caption and a function for onclick handler.

Here, the button component is re-rendered only when the props or the state of the button changes. But by default the component is re-rendered every time the parent component it updated and rendered.

In order to avoid this case we simply add a shouldComponentUpdate and check if the props change and then return the Boolean value.

class MyButton extends React.Component {
...
shouldComponentUpdate(nextProps, nextState) {
return (nextProps.caption !== this.props.caption); //Either true or false
}
render() {
return (
<button onClick={this.props.onClick}>
{this.props.caption}
</button>
)
}
}

Thus, now only when the prop caption is changed by the parent component, the button gets updated.

This improves the performance in a large scale application where you have lot of nested components in which most of the components are almost static like the above mentioned button.

There’s a lot more stuff that we can help you crack in React/React Native - we’ll come back to you with a lot more tips and tricks and you’ll have an award-winning project at the end!