Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does react decide to rerender a component

I know React has a life cycle method called shouldComponentUpdate, Which by default return true and that's how the component decides to update

But How does that life cycle method gets called, When a state or props change for that component. What actually happens when we receive new props or state? When We connect a component to redux state and mapStateToProps, Are we checking for a change in values inside the component? If not, When We are looking for a change in state or props?

when the props or state changes, how the life cycle methods are called?. Do we have a listener that calls these methods when the props or state changes?

like image 667
Shan Avatar asked Dec 03 '22 10:12

Shan


1 Answers

You should look at lifecycles of both, how they perform and in what order each method gets called. Looking at react lifecycle image bellow you can see the difference between componentWillMount and componentDidMount and others like componentDidUpdate, componentWillUpdate and so on...

Also you should reason when to use each method

To update state you call this.setState() which tells react that something has changed and it will re-render component tree. If you use this.state.data = something react won't trigger render(). Now to update props, you need to understand how render() actually works. This answer is summarized from existing anwser already:

Every time render() is called react will create a new virtual DOM where the root node is the component whose render function is called. The render() function is called when either the state or the props of a component or any of its children change. The render() function destroys all of the old virtual DOM nodes starting from the root and creates a brand new virtual DOM.

In order to make sure the re-rendering of components is smooth and efficient React uses the Diffing Algorithm to reduce the time it takes to create a new tree to a time complexity of O(n), usually time complexity for copying trees is > O(n^2). The way it accomplishes this is by using the "key" attribute on each of the elements in the DOM. React knows that instead of creating each element from scratch it can check the "key" attribute on each node in the DOM. This is why you get a warning if you don't set the "key" attribute of each element, React uses the keys to vastly increase its rendering speed.

React Lifecycle

Redux Lifecycle

enter image description here

like image 138
jank Avatar answered Jan 12 '23 01:01

jank