Helpful Tips for React.js


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

🏈 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 World</div>;
}
}

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

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

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

😸 Separate by responsibilities

According to responsibilities, we should separate React components.

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

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

function Layout(children) {
return (
<div>
<Header />
{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.',
}

😎 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!!