simple way to improve react applications performace

Before I start discussing some ways to improve the performance of react applicate, you should read the official doc from react site which already discussed about this topic.

So in my own opinion few ways to improve the performance:

1) Use stateless/function component instead of writing class as component, using stateless component will eliminate “this” from that component.

2) Use shouldComponentUpdate when necessary, lets say you have a component, lets say Dashboard, in Dashboard you have few other Components, Sidebar, Content, Footer, now you want to update prop of Sidebar, because prop is pass down from Dashboard Component, both Content and Footer will unmount and mount again, what if Content contains a map of other components, this could cause latency in your applicate. So try to add shouldComponentUpdate to Content and Footer.

  shouldComponentUpdate(nextProps, nextState) {
    if (nextProps !== this.props) {
      return true;
    }
  }

Some problem I faced with === itself, this.props contains objects that are same as nextProps but the reference is different, so that will not equal. You can find why here

So to solve this, usually I use isEqual from lodash which will performs a deep comparison between two values to determine if they are equivalent.

  import {isEqual} from "lodash";

  ... 
  shouldComponentUpdate(nextProps, nextState) {
    if(!isEqual(nextProps, this.props) {
      return true;
    }
    ...
  }

Another problem I faced sometime was, lets say I have a prop that was used both Sidebar and Content, but I don’t want to care about the prop change in content and should avoid content remount, you can do this way:

  import {isEqual} from "lodash";

  ... 
  shouldComponentUpdate(nextProps, nextState) {
    const newThisProp = {
      ...this.prop,
      iDontCareThisProp: [],
    }
    
    const newNextProps = {
      ...this.prop,
      iDontCareThisProp: [],
    }

    if(!isEqual(newThisProp, newNextProps) {
      return true;
    }
    ...
  }

By doing this you are only comparing props that you want to compare.

Hope you enjoy!