Skip to content

vinicius5581/react-rerender

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

9 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

React rerender

Because I'm using React.Component, when I've placed a setInterval in the react lifecycle method ComponentDidMount, calling this.setState every 2.5 seconds, independently of changing the value of state.score, both components, App and Score, will be re-rendered every 2.5 seconds.

image

One way to fix the problem presented on https://github.com/vinicius5581/react-rerender/commit/844a03f68d867106a1f2ca1ce4cc20c20ede24f5, is using the lifecycle method shouldComponentUpdate that returns a boolean and only when its true, the component will rerender.

The method shouldComponentUpdate takes the nextProps and nextState as props, allowing me to compare them with the current state and props. I can easly define a boolean expression comparing this.state.score and nextState.score and return true when they are different.

image

Another way to avoid unnecessary re-rendering when the value of state don't change is using React.PureComponent instead of React.Component. PureComponents do a shallow comparison of the current state with the next state and if they are the same the component won't re-render.

image

'PureComponent' will rerender if a referenced value (objects, array) gets updated even if the values don't change.

image

Releases

No releases published

Packages

No packages published