Chapter 10. Best Practices

Before delving into the best practices to be followed while dealing with React, let's recap on what we have seen so far in the earlier chapters.

We have covered the following key points:

  • What is ReactJS
  • How we can build a responsive theme with React-Bootstrap and ReactJS
  • DOM interaction with React
  • ReactJS-JSX
  • React-Bootstrap component integration
  • Redux architecture
  • Routing with React
  • React API integration with other APIs
  • React with Node.js

With the preceding topics, you should have a much clearer understanding about ReactJS, responsive themes, custom components, JSX, Redux, Flux, and integration with other APIs. I hope you have enjoyed this journey. Now we know where to start and how to write code, but it is also important to know how to write standard coding by following best practices.

In 2015, there were many new releases and conferences conducted for React across the world and now I have seen many people asking how can we write standard code in React?

Each individual will have their opinion about following best practices. I have shared some of my observations and experiences with you so far, but you might have different opinions.

If you want more detailed stuff, you can always visit React's official sites and tutorials.

Handling data in React

Whenever we have components with dynamic functionality, data comes into the picture. The same applies with React; we have to deal with dynamic data, which seems easy but it is not every time.

Sounds confusing!

Why is it easy and tough at the same time? Because, in React components, it's easy to pass properties and there are many ways to build rendering trees, but there is not much clarity about updating the views.

In 2015, we have seen many Flux libraries and with them there have been many functional and reactive solutions released.

Using Flux

In my experience, many people have misconceptions regarding Flux as to where it's not needed. They are using it because they have a good grip on that.

In our example, we have seen that Flux has a clear way to store and update the state of your application and when it is needed, it will trigger rendering.

Many times we have heard this: "There are two sides to every coin". Likewise, Flux is also beneficial as well as harmful for your code. For example, it's beneficial to declare global states for your application. Suppose that you have to manage logged in users and you are defining the state of router and active accounts; it will be painful when you start using Flux while managing temporary or local data.

From my perspective, I would not advise using Flux just in order to manage /items/:itemIdroute related data. Instead, you can just declare it within your component and you can store it there. How is it beneficial? The answer is, it will have a dependency on your component, so when your component does not exist, it will also not exist.

For example:

export default function users(state = initialState, action) { 
    switch (action.type) { 
        case types.ADD_USER: 
            constnewId = state.users[state.users.length-1] + 1; 
            return { 
                ...state, 
                users: state.users.concat(newId), 
                usersById: { 
                    ...state.usersById, 
                    [newId]: { 
                        id: newId, 
                        name: action.name 
                    } 
                }, 
            } 
 
            case types.DELETE_USER: 
            return { 
                ...state, 
                users: state.users.filter(id => id !== action.id), 
                usersById: omit(state.usersById, action.id) 
            }     
 
            default: 
            return state; 
    } 
} 

In the preceding Redux-based reducer code, we are managing the state of the application as part of the reducers. It stores the previous state and action and returns the next state.

Using Redux

As we know, in SPAs, when we have to contract with state and time, it would be difficult to handgrip state over time. Here, Redux helps a lot. How? Because, in a JavaScript application, Redux handles two states: one is the data state and another is the UI state and this is a standard option for SPAs. Moreover, bear in mind that Redux can be used with AngularJS, jQuery, or React JavaScript libraries or frameworks.

Redux is equal to Flux, really?

Redux is a tool whereas Flux is just a pattern which you can't use via plug and play or download it. I'm not denying that Redux derives some influence from the Flux pattern but we can't say it's 100% similar to Flux.

Let's go ahead to and look at a few differences.

Redux follows three guiding principles, as follows. We will also cover some differences between Redux and Flux.

Single-store approach

We have seen in earlier diagrams that the store is pretending to be an intermediary for all kinds of state modifications within applications and Redux is controlling the direct communication between two components through the store with a single point of communication.

Here the difference between Redux and Flux is: Flux has multiple store approaches and Redux has a single-store approach.

Read-only state

In React applications, components cannot change state directly but have to dispatch changes to the store through actions.

Here, the store is an object and it has four methods, as follows:

  • store.dispatch(action)
  • store.subscribe(listener)
  • store.getState()
  • replaceReducer(nextReducer)

Reducer functions to change the state

Reducer functions will handle dispatch actions to change the state as the Redux tool doesn't allow direct communication between two components; thus it will also not change the state but the dispatch action will be described for the state change.

Reducers here can be considered pure functions and the following are a few characteristics for writing reducer functions:

  • No outside database or network calls
  • Returns values based on its parameters
  • Arguments are immutable
  • The same argument returns the same value

Reducer functions are called pure-functions as they are doing nothing except returning a value based on their set parameters; they don't have any other consequences.

In Flux or Redux architecture, it's always tough to deal with nested resources from an API's return, so it's recommended to have a flat state in your component such as normalize.

A hint for pros:

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

Immutable React state

In a flat state, we have the benefit of dealing with nested resources and immutable objects, along with the benefit, that a declared state cannot be modified.

The other benefit of immutable objects is that, with their reference level equality checks, we can have fabulously improved rendering performance. For example, with immutable objects there is shouldComponentUpdate:

shouldComponentUpdate(nexProps){ 
    // instead of object deep comparsion 
    returnthis.props.immutableFoo!==nexProps.immutableFoo 
} 

In JavaScript, the use of the immutability deep freeze node will help you to freeze nodes before mutation and then it will verify the results. The following code example shows the same logic:

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

I hope that the preceding examples have clarified Immutable.js and its benefits. It also has uncomplicated methods but it isn't much used:

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

From my point of view, it's a very fast and beautiful feature to use.

Observables and reactive solutions

Quite often, I have heard people asking about the alternatives to Flux and Redux, as they want more reactive solutions. You can find some alternatives in the following list:

  • Cycle.js: This is a functional and reactive JavaScript framework for cleaner code.
  • .rx-flux: This is the flux architecture with an add on, RxJS.
  • redux-rx: This is the utilities of RxJS, used for Redux.
  • Mobservable: This comes with three different flavors--observable data, reactive functions, and simple code.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset