Yeah hooks are good, but have you tried faster React Components?

5 simple tips to improve the performance of a React application

Image for post
Image for post
Illustration by Omar Benseddik

About the render function

Which render function?

class Foo extends React.Component { render() {
return <h1> Foo </h1>;
}

}
function Foo() {
return <h1> Foo </h1>;
}

When does render happen?

What happens in the render function?

Tip #1: Avoid unnecessary render calls by carefully distributing the state

Tip #2: Make fewer state updates

// initial state
{ limit: 7, numbers: [0, 1, 2, 3, 4, 5, 6]
// change limit -> 4
render 1: { limit: 4, numbers: [0, 1, 2, 3, 4, 5, 6] } //
render 2: { limit: 4, numbers: [0, 2, 3]

Tip #3: Avoid unnecessary render calls with PureComponent and React.memo

const Bar = React.memo(function Bar({name}) {
return <h1>{name}</h1>;
});
class Bar extends React.PureComponent {
render() {
return <h1>{name}</h1>;
}
}

Should every component be a PureComponent or memo?

Problem with nested objects

// expected behavior with primitive values
shallowCompare({ name: 'bar'}, { name: 'bar'}); // output: true
shallowCompare({ name: 'bar'}, { name: 'bar1'}); // output: false
// unexpected behavior with primitive values
shallowCompare({ name: {first: 'John', last: 'Schilling'}, {first: 'John', last: 'Schilling'}); // output: false

Problem with function props

Tip #4: Writing better props

<Bar firstName="John" lastName="Schilling" />
class App extends React.Component{  constructor(props) {
this.doSomethingMethod = this.doSomethingMethod.bind(this);
}
doSomethingMethod () { // do something}

render() {
return <Bar onSomething={this.doSomethingMethod} />
}
}

Tip #5: Controlling the update

const Bar = React.memo(
function Bar({ name: { first, last } }) {
console.log("update");
return (
<h1>
{first} {last}
</h1>
);
},
(prevProps, newProps) =>
prevProps.name.first === newProps.name.first &&
prevProps.name.last === newProps.name.last
);

Conclusion

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

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