Helpful Tips for React.js


In this article, I will introduce helpful tips to improve React development efficiency.

🐰 Remove .bind(this)

We can lose .bind(this) by using arrow function.

import React, { Component } from "react";

export class Button extends Component {
state = { toggle: false };

render() {
const toggle = this.state.toggle;

return (

.toggleButton}>{toggle ? "ON" : "OFF"}</button>
div>
);
}

toggleButton = () => {
this.setState(prevState => ({ toggle: !prevState.toggle }));
};
}

😀 Stateless functional components

We should use “Stateless functional components”, if it is possible.

// Bad
class App extends React.Component {
componentDidMount() {
console.log('Called componentDidMount');
}
render() {
return <div>Hello Worlddiv>;
}
}

// Good
import { compose, lifecycle, pure } from 'recompose'

compose(
lifecycle({
componentDidMount() {
console.log('Called componentDidMount');
}
}),
pure
})(function App () {
return <div>Hello Worlddiv>;
})

HOC + Functional Stateless Component is a good solution in stateless functional components.

🚌 Separate components by responsibilities

According to responsibilities, we should separate React components.

// Bad
class Layout extends React.Component {
renderHeader() {
return <header />;
}
render() {
return (

{this.renderHeader()}
{this.props.children}
div>
);
}
}

// Good
function Header() {
return <header />;
}

function Layout(children) {
return (


{children}
div>
)
}

🐮 Use object-rest-spread

Let’s use object-rest-spread to update difference ditection in React state.

// object-rest-spread
let n = { x, y, ...z };
n; // { x: 1, y: 2, a: 3, b: 4 }

🚜 Follow Flux Standard Action

Flux Standard Action is a human-friendly standard for Flux action objects.

// Good
{
type: 'ADD_TODO',
payload: {
text: 'Do something.'
}
}

// Bad
{
type: 'ADD_TODO',
text: 'Do something.',
}

🐯 Duplicated lifecycle methods

Please be careful the following methods. In the feature, them will be un-usable. It is useful command: reactjs/react-codemod.

  • componentWillMount
  • componentWillReceiveProps
  • componentWillUpdate

😸 Special Thanks

🖥 Recommended VPS Service

VULTR provides high performance cloud compute environment for you. Vultr has 15 data-centers strategically placed around the globe, you can use a VPS with 512 MB memory for just $ 2.5 / month ($ 0.004 / hour). In addition, Vultr is up to 4 times faster than the competition, so please check it => Check Benchmark Results!!