pasoc30
pasoc30

Reputation: 141

React: Is a component entirely re-rendered on every setState()?

Just got a bit confused about the lifecycle in react. Here's my understanding...

The render() always run first, right? If so...
It implies that a setState() inside useEffect() only runs after the initial render(), correct?

Question:
When the above happens, does the entire component re-render?
So that would be a second time the component renders just to load a state.
Wouldn't that be a performance issue?

Upvotes: 3

Views: 505

Answers (2)

Zohaib
Zohaib

Reputation: 1037

On every state change render is called again but not whole component renders again.

React keeps Two DOM Tree Objects in memory:

  1. Virtual DOM
  2. Real DOM

React have a very intelligent and powerful diffing algorithm which calculates difference between previous DOM state and Next DOM state called Reconciliation process.

Only those sub elements which have changed would be re-rendered.
Keys help React identify which items have changed, are added, or are removed.
Keys should added to list or array elements , to give those elements a stable identity

enter image description here

For example, you want to delete <input key="i42"/> element from your list so on left side Its Actual DOM Tree Object and on Right side its Virtual DOM tree object. React calculates difference between two and only the difference will be Recreated Intelligently.

https://reactjs.org/docs/lists-and-keys.html

https://reactjs.org/docs/reconciliation.html#the-diffing-algorithm

Upvotes: 7

royranger
royranger

Reputation: 374

So the thing about React is that there are two DOMs -- one is the actual DOM, and the other is the virtual DOM. Every time there is a state change, the virtual DOM re-renders. React then compares the changes to the virtual DOM vs changes to the real DOM, and only updates the real DOM with what has actually changed. Re-rendering the virtual DOM is not a performance issue as it's super quick.

There's a cool article you can read about this

Upvotes: 1

Related Questions