ReactJS best practices for 2016 (part one)

2015 was the year of React with tons of new releases and conferences dedicated to the subject all over the world. For a detailed list of key dates from last year, take a look at the React 2015 Wrap Up.

The most interesting question of 2016: How to code an app and what are the recommended libraries?

As a developer working for a long time with React.js, I have my little idea and my best practices but it is possible that you will not agree with me so in this case, do not hesitate to drop a comment in order to open the discussion.

react_best_practices-1453211146748

If you are new to React.js, watch this tutorial React.js or React howto by Peter Hunt.

Manage data

Manipulating data is both easy and challenging. This is because there are multiple ways to pass a property to a React component in order to build the render tree, however it's not always obvious how to update the view.

2015 started with the release of several Flux libraries and continued with more functional and responsive solutions.

Let's look at where we are today.

Flux

In our experience, Flux is often overused (i.e. used when there is no real need).

Flux provides a clean way to store and update application state and trigger on-demand rendering.

It is useful for managing global application states such as: managing connected users, the status of a router or an active account, but it can quickly become tedious if you start managing temporary or local data.

We don't recommend using Flux to handle routing-related information like items/:itemId. Instead, it is better to load and store in the “state” of the component. This way it will be destroyed when the component disappears.

For more info on Flux The Evolution of Flux Framework is a great article.

Use redux

Redux is a predictable state container for JavaScript apps.

If you think you need Flux or a similar solution, you should look at Redux and the course of Dan Abramov : Getting started with redux to quickly increase your skills.

Redux is built around the ideas of Flux but avoids complexity by drawing inspiration from ELM.

Keep the States flat

APIs typically return nested resources. Which can be difficult to manage in an architecture based on Flux or Redux. We recommend flattening them with a library like normalize and keep your states as flat as possible.

Tip for the pros:

const data = normalize(response, arrayOf(schema.user))
state = _.merge(state, data.entities)

(we are using isomorphic-fetch to communicate with the APIs)

Use immutable States

“shared mutable states are the source of evil” Pete Hunt, React.js Conf 2015

immutable_logo_for_react_js_best_practices-1453211749818

Un immutable object is an object whose state cannot be changed after being created.

Immutable objects can save us a lot of headaches and improve rendering performance with their equality check at the reference level. As in the shouldComponentUpdate :

shouldComponentUpdate(nexProps) {
   // au lieu d'une comparaison profonde
   return this.props.immutableFoo !== nexProps.immutableFoo
}

How to achieve immutability in javascript?

The hard way is to be very careful and write code like the example below, which you should always unit test with deep-freeze-node (freezer before the mutation and check the result afterwards).

return {
  ...state,
  foo
}
return arr1.concat(arr2)

And believe me, those were the easy examples.

The simplest, but also the least natural way is to use Immutable.js.

import { fromJS } from 'immutable'
const state = fromJS({ bar: 'biz' })
const newState = foo.set('bar', 'baz')

Immutable.js is fast, and the idea is elegant. I recommend you to watch the video Immutable Data and React video by Lee Byron even if you don't want to use it. This will allow you to understand how it works in depth.

Observable and reactive solutions

If you don't like Flux/Redux or want the service to be more responsive, don't worry!  IThere are other solutions to manage your data. Here is a list of bookstores that correspond to what you are looking for:

  • cycle.js (“A functional library and a responsive JavaScript framework for cleaner code”)
  • rx-flow (“The Flux Architecture with RxJS”)
  • redux-rx (“RxJS utilities for Redux.”)
  • mobservable (“Observable data. Reactive functions. Simple code.”)

Routing

Almost all client applications use routing. If you're using React.js in a browser, at some point you'll need to use a library. We chose react-router by the great community Rackt. Rackt always produces quality resources for React.js lovers.

To integrate react-router, take a look at their documentation, but the most important thing is that if you are using Flux/Redux, we recommend to keep the state of your router in sync with your state store/global.

Synchronized router-states will help you control router behavior through Flux/Redux actions and read router states and settings in your components.

Redux users can do this simply with the library redux-simple-router.

Code splitting, lazy loading

Very few users of webpack know that it is possible to separate the code of your application in order to split the output of the bundler into several JavaScript chunks:

require.ensure([], () => {
  const Profile = require('./Profile.js')
  this.setState({
    currentComponent: Profile
  })
})

This is very useful in long applications because the user's browser does not have to download the code which is rarely used like the profile page after each deployment.

More chunk means more HTTP requests but that's not a problem with HTTP/2 multiplexed.

You can also combine with chunk hashing in order to optimize your cache hit ratio after code changes…

The next version of react-router will bring a lot in terms of code splitting.

To understand the future of react-router, check out this blog post by Ryan Florence: Welcome to Future of Web Application Delivery.

The rest of the article

Original article de Peter Marton RisingStack translated by the JS-Republic team

[separator type=”” size=”” icon=”star”] [actionbox color=”default” title=”” description=”JS-REPUBLIC is a service company specializing in JavaScript development. We are an approved training center. Find all our technical training on our partner site dedicated to Training” btn_label=”Our training” btn_link=”http://training.ux-republic.com” btn_color=”primary” btn_size=”big” btn_icon=”star” btn_external =”1″]