Optimising React Performance

Image for post
Image for post

◉ React Optimisations

Changes = Diff(UI1, UI2)

◉ Measuring First

Import Perf from 'react-addons-perf'
Perf.start();
// use the app
Perf.stop();
Perf.printWasted();
Image for post
Image for post

◉ Should React Update The Component?

function shouldComponentUpdate(nextProps, nextState) {
return true;
}
function shouldComponentUpdate(nextProps, nextState) {
return nextProps.id !== this.props.id;
}

◉ Using a React.PureComponent

◉ Making Data Immutable

More React App Optimization Techniques

◉ Using the Production Build

◉ Binding Functions Early

// Creates a new `handleUpload` function during each render()
<TopBar onUpload={this.handleUpload.bind(this)} />
class App extends React.Component {
constructor(props) {
super(props);
this.handleUpload = this.handleUpload.bind(this);
}
render() {

<TopBar onUpload={this.handleUpload} />

}
}

◉ Using Multiple Chunk Files

◉ Enabling Gzip on Your Web Server

◉ Using Eslint-plugin-react

Code splitting in React.js

Example

// app.js
import { total } from './math.js';
console.log(total(10, 20)); // 42
// math.js
export function total(a, b) {
return a + b;
}

Bundle

function total(a, b) {
return a + b;
}
console.log(total(10, 20)); // 30

Before

import { total } from './math';
console.log(total(10, 20));

After

import("./math").then(math => {
console.log(math.total(10, 20));
});
import TestComponent from './ TestComponent ';
function LazyComponentLoadExample() {
return (
<div>
< TestComponent />
</div>
);
}

After

const TestComponent = React.lazy(() => import('./TestComponent'));
function LazyComponentLoadExample() {
return (
<div>
<TestComponent />
</div>
);
}

Use of suspense

const TestComponent = React.lazy(() =>import('./TestComponent'));
function SuspenseComponentExample() {
return (
<div>
<Suspense fallback = {<div>Loading...</div>}>
<TestComponent />
</Suspense>
</div>
);
}

◉ Route based code splitting

import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import React, { Suspense, lazy } from 'react';
const Customer = lazy(() = > import('./routes/Customer'));
const Admin = lazy(() = > import('./routes/Admin'));
const App = () = > (
<Router>
<Suspense fallback = {<div>Loading...</div>}>
<Switch>
<Route exact path = "/" component = {Customer}/>
<Route path = "/admin" component = {Admin}/>
</Switch>
</Suspense>
</Router>
);

Experience with Front-end Technologies and MERN / MEAN Stack. Working on all Major UI Frameworks like React, Angular.

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