Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why React does't compare Previous State and New State before re rendering? Why it always render when setState is called?

Tags:

reactjs

If React compares (Shallow) previous state and next state before re-rendering, it will reduce many renders which helps to optimize performance.

According to React docs, React always render component and their children when the setState method is called. Should React smartly handle unwanted re-rendering of a component and their children.

like image 923
shah chaitanya Avatar asked Oct 16 '22 15:10

shah chaitanya


1 Answers

React can be used with Immutable or plain Javascript data. And React does provide for a lifecycle hook(shouldComponentUpdate) which you can choose to use in order to prevent re-render. However for a plain Javascript data sometimes it can be an overhead to compare data and decide whether to re-render the data or not since it may so happen that in order to check for data change, you may need to deep compare the data and in cases where most often a re-render is needed, react has to make the DOM updates after a comparison state which may be more costly then simple Virtual DOM diffing and updating.

That being said, you can achieve a tradeoff between a quick decision of whether to re-render or not actually rendering using a PureComponent and/or ImmutableJS data.

like image 144
Shubham Khatri Avatar answered Oct 26 '22 23:10

Shubham Khatri