Hans
Hans

Reputation: 2832

How is Virtual DOM updated?

Imagine that you've built an application with ReactJs containing a hundred elements. Let's say that in some time, the state of component A changes, and for the sake of simplicity we assume it has only one element and no child component.

My question is: how is Virtual DOM updated in response to the state change?

After a few hours of research, I found two contradictory opinions:

Unfortunately, official documentation is not clear about this. So, can anybody give the correct answer? (please with supporting reference)

Upvotes: 2

Views: 633

Answers (1)

Quentin Grisel
Quentin Grisel

Reputation: 4987

[Edit] : Some parts are imcomplete here, think about reading the comment section !


React update a component when its state or a prop changes. It does a comparison between the previous JSX and the new one and re-render only the differences.

If the parent component has its state or a prop changed, it will be updated. The child will not be refreshed unless a prop from the parent that is passed to it changes.

Note that the useEffect from the child is triggered first. Knowing that, If you do things that update the state in the child component, then it will be re-rendered everytime (Because the usEffect is triggered everytime if you don't set any dependencies).

Test from Stackblitz - Child Effect is triggered first

Article that made me notice it (I didn't know before this answer :D)

Here is how I understand things in React. To be short, the entire virtual DOM isn't rebuilt from scratch, it's not how JSX comparison works.

I don't have much sources about what I said, but here is the explanation about jsx update from the official documentation. Just that should be enough to eliminate the first point of your list.

Upvotes: 2

Related Questions