Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does React always check the whole tree?

Tags:

reactjs

When a component is updated by calling setState, does React run the diffing algorithm on the whole DOM tree, or only on the part of it that belongs to the updated component?

For example, if I have 10000 components in my app and call setState in a component that has no children (it's a leaf of the tree), will React go through the whole large DOM tree (which would be slow) or only the DOM tree generated by the component (which would be a lot faster)?

like image 589
Michal Miškerník Avatar asked Jan 09 '16 17:01

Michal Miškerník


People also ask

Which statement is true about Reactjs?

Answer: D is the correct option. React. js is a free, open-source front-end JavaScript library used for building user interfaces or UI components.

What are error boundaries in Reactjs?

Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed. Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them.

How does React know what to re render?

React schedules a render every time the state of a component changes. Scheduling a render means that this doesn't happen immediately. React will try to find the best moment for this. Changing the state means that React triggers an update when we call the setState function (in React hooks, you would use useState ).

How does React work behind the scenes?

React goes through its virtual DOM ,creates a list of those changes that need to be made to the actual DOM and then does it all in one single process. In fancy words, React does batch updates. So putting all pieces together, Reconciliation = Render + Diffing occurs in between + Commit.


1 Answers

No, React will not go through the whole tree when you called setState only on a leaf node.

On call of setState, react will only re-render the component (tree node) for which setState was called on and any components (nodes) which are children. It should be noted that React will only update the DOM if there is actually a change to be represented from the call to setState.

Vjeux, one of the members of the React team, wrote a good blog post detailing how the react diff algorithm works, and how it works when you call setState. Here is the link.

like image 51
Mike Wilcox Avatar answered Nov 07 '22 04:11

Mike Wilcox