Andrew Kang
Andrew Kang

Reputation: 328

React PureComponent vs Component in case of counts of rendering same

In a React class module, If counts of rendering in PureComponent are same as ones of it in Component, which one should I use? PureComponent is always faster, better than Component?

render(){

       //console.log('rendered');

return(<div>...

}

Upvotes: 0

Views: 72

Answers (2)

Utsav Patel
Utsav Patel

Reputation: 2889

Without measuring, it is hard to say.

PureComponent is nothing fancy, it justs handles shouldComponentUpdate method automatically for you.

shouldComponentUpdate(nextProps, nextState) {
    return stuffChanged(this, nextProps, nextState))
  }

Let's say stuffChanged is a function which does heavy computation and thus takes considerable amount of time too.

So now react will spend time in running this function (diffing) and then also in updating the DOM.

Whereas, if you did not have shouldComponentUpdate method, then your component will not have to spend time in running stuffChanged expensive function.

It will update the DOM if diffing and reconciliation of react tells it to.

So, if you just have a Component there is one diff i.e updating the DOM.

But if you have a PureComponent there is atleast one diff and sometimes two i.e diffing for state and props and then updating the DOM.

Which means PureComponent is going to be slower usually but faster occasionally.

Unless you have measured your performance of the app with some profiling tool, I would suggest you to just stick to Component.

If you wrap use PureComponent everywhere without measuring, chances are you would end up slowing your web app.

Upvotes: 2

Edgar Cuarezma
Edgar Cuarezma

Reputation: 125

If said component doesn't have many changing parts (ie, different state or props) then pure component is a simplified way of making sure it doesn't re-render needlessly. Otherwise, use componenetDidUpdate would be a more in-depth way to handle those

Upvotes: 0

Related Questions