'React: Impact of conditional rendering on performance
Does it make more sense to conditionally render a popup (e.g. loading spinner popup via {shouldShowLoading && <LoadingSpinner />}) further down or up in the component tree? So which of the following two options is favorable - or is there no difference in performance?
Further down in the component hierarchy (e.g. positioned at a leave close to the button which triggers the popup)? - e.g. at following arrow position
App.tsx / \ Header.tsx Counter.tsx / \ --> HeaderElement.tsx HeaderElement.tsx / Badge.tsxwith such pseudo code:
const HeaderElement = () => { // ... shouldShowLoading is defined here return ( <div> <Title /> {shouldShowLoading && <LoadingSpinner />} </div> ); }
or instead
...further up (e.g. in the root next to the main navigation)? - e.g. at following arrow position
--> App.tsx / \ Header.tsx Counter.tsx / \ HeaderElement.tsx HeaderElement.tsx / Badge.tsxwith such pseudo code:
const App = () => { // ... shouldShowLoading is defined here or in global state return ( <div> < RootNavigation /> {shouldShowLoading && <LoadingSpinner />} </div> ); }
My thoughts and investigations so far:
React's reconciliation algorithm always creates a second virtual tree of your DOM (computationally cheap), but ultimately renders only the subtrees that have actually changed compared to the existing virtual DOM tree, because rerenderings are computationally expensive.
So does conditional rendering in App.tsx (as shown above) cause everything below it (i.e. the entire app) to rerender? - I believe that isn't the case but, after reading more about React's reconciliation algorithm in the React docs I still can't say why..
Question:
Who can explain to me why in the case of conditional rendering not all children components necessarily have to rerender? Which kind of special heuristic is the reconciliation algorithm using? Or am I wrong?
Solution 1:[1]
Whether App.tsx chooses to conditionally render its descendants is not equivalent to whether the subtrees have changed.
The children may have no dependencies that cause them to change.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Webber |
