Make React.js App fast

How fast is fast? It depends on various conditions. But it’s always better to make the app as fast as possible.

Recat.js is fast enough, even you don’t do anything. But there are something more we can do to make it even better, except using PureComponent or ShouldComponentUpdate function.

First, remember JSX is just a syntax sugar. Everything in React.js Component is a function. <div> will be transipiled to React.CreateElement(“div”, {…props}, {…children}). So for the following code, in fact the first line is already calling a function.

let someChild = (<SomeComponent ...props />);
if (condition) {
someChild = (<SomeOther ...props />);
}

It’s not that expensive. But if “condition” is true, the first function call to generate a component is useless. Then it may be better to do like this:

let someChild; 
if (condition) {
someChild = (<SomeOther ...props />);
} else {
someChild = (<SomeComponent ...props />);
}

Second, be careful when using .bind(this, someArgument) inside the JSX.

render() {
return
(<div>
<SomeComponent1 propChanged />
<SomeComponent2 onClick={someFunc.bind(this, "test")} />
</div>);
}

Every time, when the render function is called, even SomeComponent2 does not need to be re-rendered, even SomeComponent2 extends from React.PureComponent, it is re-rendered, because the onClick prop is changing, unless ShouldComponentUpdate purposely omits the check for this function.

Third, try to keep the stateful component as small as possible. When using setState, it will cause a re-render, and if the state is inside the parent, basically, all the children will be re-rendered too.

For example, open / close state should be in the component that is using it. This can also effect the .bind() using. Like if you pass the name of a component into it, then you can use this.props.name to reference it. No need to use .bind(this, “name”) inside JSX.

Fourth, if the web app is doing a lot of DOM manipulation, it’s better to think of using some lib like fastdom. It will batch all the DOM manipulations and do it in the next requestAnimationFrame cycle. This is mainly because you don’t need to think about the order of all the components that are doing DOM changes in ComponentDidMount or ComponentDidUpdate. fastdom will handle this situation.

Last, if we don’t need Redux, MobX or Flux, then don’t use a store lib. If the app is small and has only a few state, then we may not need Redux, although it’s quite small. Using local state inside the app is totally good and doing ajax inside the component is fine too, as long as it’s clean and well structured.

Enjoy coding. :)

Show your support

Clapping shows how much you appreciated Sho Mukai’s story.