Best practices in React and Flux

Introduction

React is a wonderful class library which can be used to develop rich client application by ensuring better performance. Flux is the architecture which gives the beauty of uni-directional data flow and immutability of data. React+Flux is always a good choice while you starting your web application.I would like to share some thoughts on the good practices we can follow while developing an app using react and flux.

No direct store update

The unidirectional data flow gives the beauty of single source of truth, however it is a choice. Flux doing nothing to prevent you making it bidirectional, you can always update the store from your component directly with out initiating an action creator and action. If you want to follow flux don’t do this.

Call setState appropriately

One another mistake is calling setstate inside render. You can call setState anywhere other than render. However try to avoid unconditional setstate inside componentDidupdate() as it may lead to infinite re-rendering since didUpdate calls whenever a component has re-rendered.

Avoid updating the DOM directly and use ref wisely

Since react is doing the job of DOM update using virtual DOM it is a bad practice to update the DOM directly using conventional methods.Instead use ref to read the DOM and update the DOM react way by calling setState and re-rendering.

Always use unique key to the components

React internally identifies the components using key so it is important to make sure that you are using unique names for the react components.

vDo not add listeners in willReceiveProps or didUpdate().

Do not add event listeners in componentDidUpdate() and componentWillReceiveProps()

Adding event listeners in didUpdate and willReceiveprops is a bad idea as both life cycle events (willReceiveprops is deprecated from the latest version 16.4 onward) will trigger more than once based on props change or state change. So adding listeners in those event cause multiple reference of the event listeners and cause memory leak.

Stateless as much as possible and Tiny Components

It is always good to go for the stateless and tiny components whenever possible. This can improve the performance by avoiding the life cycle.

Bind the callback functions inside the constructor

Avoid binding the context while passing a call back function as prop to child component. If you are passing like that it will be creating a new reference every time and cause re-render of your pure child component. Instead bind the context in constructor and pass the same as prop.

class Parent extends React.Component{
  constructor(){
    // Bind the context here
    this.callBackFunc = this.callBackFunc.bind(this)
  }
  
  render(){
    return ( <Child callBack={this.callBackFunc});
  }
}

Leave a Reply

Your email address will not be published. Required fields are marked *