React.js Best Practices for 2016

Source: Internet
Author: User
Tags es6 class

By the year of React with tons of new releases and developer conferences dedicated to the topic all over the world. For a detailed list of the most important milestones of last year, check out our React on wrap up.

The most interesting question for 2016:how should we write a application and what is the recommended libraries?

As a developer working for a long time with react.js I had my own answers and best practices, but it's possible that's you Won ' t agree on everything with me. I ' m interested in your ideas and opinions:please leave a comment so we can discuss them.

React.js logo-best Practices for 2016

If you is just getting started with react.js, check out our react.js tutorial, or the React howto by Pete Hunt.

Dealing with Data

Handling data in a react.js application are super easy and challenging at the same time.

It happens because you can pass the properties to a React component in a lot of ways to build a rendering the tree from it; However it ' s not always obvious how do you should update your view.

Started with the releases of different Flux libraries and continued with more functional and reactive solutions.

Let's see where we is now:

Flux

According to We experience, Flux is often overused (meaning that people use it even if they don ' t even need it).

Flux provides a clean-out to store and update your application's state and trigger rendering when it ' s needed.

Flux can be useful for the app's global states like:managing logged in user, the state of a router or active account but It can turn quickly into pain if your start to manage your temporary or local data with it.

We don ' t recommend using Flux for managing route-related data Like/items/:itemid. Instead, just fetch it and store it in the your component ' s state. In this case, it'll be destroyed when your component goes away.

If you need more info on flux, the Evolution of flux frameworks is a great read.

Use redux

Redux is a predictable state container for JavaScript apps.

If you think your need Flux or a similar solution you should check out redux and Dan Abramov ' s Getting started with Redux C Ourse to quickly boost your development skills.

Redux evolves the ideas of Flux but avoids it complexity by taking cues from ELM.

Keep your state flat

API ' s often return nested resources. It can be hard-to-deal with them in a Flux or redux-based architecture. We recommend to flatten them with a library like NORMALIZR and keep your state as flat as possible.

Hint for Pros:

Const DATA = normalize (response, arrayof (Schema.user))

State = _.merge (state, Data.entities)

(We use Isomorphic-fetch to communicate with our APIs)

Use immutable states

Shared mutable state was the root of all Evil-pete Hunt, React.js Conf 2015

Immutable logo for react.js best practices 2016

Immutable object is a object whose state cannot was modified after it is created.

Immutable objects can save us all a headache and improve the rendering performance with their reference-level equality Che Cks. Like in the Shouldcomponentupdate:

Shouldcomponentupdate (nexprops) {

Instead of object deep comparsion

return This.props.immutableFoo!== Nexprops.immutablefoo

}

How to achieve immutability in JavaScript?

The hard-to-be-be-careful and write code like the example below, which-you-should always check in your unit tests with Deep-freeze-node (freeze before the mutation and verify the result after it).

return {

... state,

Foo

}

Return Arr1.concat (ARR2)

Believe me, these were the pretty obvious examples.

The less complicated-on-the-also-natural one 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 behind it is beautiful. I recommend watching the immutable Data and React video by Lee Byron even if you don ' t want to use it. It would give deep insight into understand how it works.

Observables and Reactive Solutions

If you don't like flux/redux or just want to being more reactive, don't be disappointed! There is solutions to deal with your data. Here's a short list of libraries What's probably looking for:

Cycle.js ("A Functional and reactive JAVASCRIPT framework for cleaner Code")

Rx-flux ("The Flux Architecture with RxJS")

Redux-rx ("RxJS Utilities for redux.")

Mobservable ("Observable data. REACTIVE functions. Simple code. ")

Routing

Almost every client side application has some routing. If you is using React.js in a browser, you'll reach the point when you should pick a library.

Our chosen one are the React-router by the excellent rackt community. Rackt always ships quality resources for react.js lovers.

To integrate React-router check out their documentation, but what's more important here:if your use Flux/redux we recommen D to keep your router ' s state in sync with your Store/global state.

Synchronized router states would help you to control router behaviors by Flux/redux actions and read router states and Para meters in your.

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

Code Splitting, lazy loading

Only a few of webpack users know that it's possible to split your application's code to separate the bundler ' s output to M Ultiple JavaScript Chunks:

Require.ensure ([], () = {

Const PROFILE = require ('./profile.js ')

This.setstate ({

Currentcomponent:profile

})

})

It can be extremely useful in large applications because the user ' s browser doesn ' t has to download rarely used codes lik E The profile page after every deploy.

Have more chunks would cause more HTTP requests-but that's not a problem with HTTP/2 multiplexed.

Combining with chunk hashing you can also optimize your cache hits ratio after code changes.

The next version of React-router would help a lot in code splitting.

For the future of React-router check out this blog post by Ryan Florence:welcome to the Web application Delivery.

Components

A lot of people is complaining about JSX. First of all, you should know that it's optional in React.

At the end of the day, it'll be compiled to JavaScript with Babel. You can write the JavaScript instead of JSX, but it feels the more natural to the use JSX while you is working with HTML.

Especially because even less technical people could still understand and modify the required parts.

JSX is a JavaScript syntax extension this looks similar to XML. You can use a simple JSX syntactic transform with React. -JSX in depth

If you want to read more about JSX check out the JSX Looks like an abomination-but it's good for you article.

Use Classes

React works well with ES2015 classes.

Class HelloMessage extends React.component {

Render () {

return <div>hello {this.props.name}</div>

}

}

We prefer higher order us leaving Createclass is more than mixins a syntactical question rather th An a technical one. We believe there is nothing wrong with using Createclass over React.component and Vice-versa.

PropType

If you still don ' t check your properties, you should start with fixing this. It can save hours for you, believe me.

Mycomponent.proptypes = {

IsLoading:PropTypes.bool.isRequired,

Items:ImmutablePropTypes.listOf (

Immutableproptypes.contains ({

Name:PropTypes.string.isRequired,

})

). isrequired

}

Yes, it's possible to validate Immutable.js properties as well with React-immutable-proptypes.

Higher order Components

Now that Mixins is dead and not supported in ES6 Class, we should look for a different approach.

What is a higher order component?

PassData ({foo: ' Bar '}) (MyComponent)

Basically, compose a new component from your original one and extend its behaviour. You can use it on various situations like Authentication:requireauth ({role: ' admin '}) (MyComponent) (check for a user in Higher component and redirect if the user is not logged in) or connecting your component with Flux/redux store.

At Risingstack, we also like to separate data fetching and controller-like logic to higher order components and keep our V Iews as simple as possible.

Testing

Testing with good test coverage must is a important part of your development cycle. Luckily, the React.js community came up with excellent libraries to help us achieve this.

Component Testing

One of our favorite libraries for component testing are enzyme by AIRBNB. With it's shallow rendering feature you can test logic and rendering output of your components, which is pretty amazing. It still cannot replace your selenium tests, but the can step up to a new level of frontend testing with it.

It (' Simulates click events ', () = {

Const OnButtonClick = Sinon.spy ()

Const Wrapper = Shallow (

<foo Onbuttonclick={onbuttonclick}/>

)

Wrapper.find (' button '). Simulate (' click ')

Expect (onbuttonclick.calledonce). to.be.true

})

Looks neat, isn ' t it?

Do I use Chai as assertion library? You'll like chai-enyzime!

Redux Testing

Testing a reducer should is easy, it responds to the incoming actions and turns the previous state to a new one:

It (' should set token ', () = {

Const NEXTSTATE = reducer (undefined, {

Type:user_set_token,

Token: ' My-token '

})

Immutable.js State output

Expect (Nextstate.tojs ()). TO.BE.EQL ({

Token: ' My-token '

})

})

Testing actions are simple until you start to use async ones. For testing Async Redux actions we recommend to check out the Redux-mock-store, it can help a lot.

It (' should dispatch action ', (done) = {

Const GetState = {}

Const ACTION = {type: ' Add_todo '}

Const EXPECTEDACTIONS = [Action]

Const STORE = Mockstore (getState, expectedactions, done)

Store.dispatch (Action)

})

For deeper redux testing visit the official documentation.

Use native react to develop a profitable financial assistant app ing

React.js Best Practices for 2016

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.