React Element’s “Parent” vs “Rendered By”
A key concept of React we tend to forget, quickly explained.
When I debug functionality and performance in a React app, I always keep in mind the difference between who created a certain element vs. it’s parent vs. the reason for it’s render. I would like to share my experience in this regard with you.
Meet App, Parent, and Child. They would be the React components we use to understand React life-cycle a little bit better using the following sandbox.
When App (re-)renders, the flow is as follows:
1. Child elements are created by App and passed to the element creation of the Parent Element as the “children” prop.
React Element Creation Order
App ➜ Child ➜ Parent
It’s very easy to see by looking at the traspiled version of App.
2. Render functions are called in their order in the React Virtual DOM hierarchy.
React Element Render Order
App ➜ Parent ➜ Child
3. The elements are then mounted in the opposite order, from the bottom of the hierarchy.
React Element Mount Order
Child ➜ Parent ➜ App
Points 2 and 3 can be seen by the logs produced in the sandbox:
Notice that Parent is not the one that creates Child elements. They are passed to Parent in the
children prop. To prove it, notice that when we click on the “increase” button, only the Parent is re-renders and uses the same children passed to it by App without re-rendering them.
Child elements are rendered by App, and would be re-rendered whenever App re-renders.
This examples helps us to settle the difference between React element’s “parent” element and “rendered by” element.
This is a very important difference to keep in mind when debugging functionality and performance. React element’s “rendered by” can be found when inspecting it using React Developer Tools.
So next time a component re-renders unexpectedly, don’t automatically blame it’s father for it. Open React Developer Tools to find the real element that’s responsible for it.
Check it out for yourself: