3

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?

4
  • I thought React only re-rendered the sub-elements that change, not all elements. Commented Apr 11, 2020 at 5:01
  • I see, so only the sub-elements that depend on that state will re render when the state changes? Did i get it correctly? Commented Apr 11, 2020 at 5:06
  • I've heard something along those lines, not 100% sure though. Commented Apr 11, 2020 at 5:08
  • renders are usually super fast, unless you huge DOM structure. Also, only the changed parts go to the DOM anyway Commented Apr 11, 2020 at 5:10

2 Answers 2

7

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.