Under the Hood: ReactDOM.render()
The following article will go into the steps that are performed whenever we attach a component to a DOM element using ReactDOM.render()
.
To illustrate the steps let’s start by calling the method in line 5 of the following code snippet:
Notice that we pass two arguments: a component
and a container
(node of the DOM). This will render a component to the DOM. But, what happens under the hood?
react-dom
Let’s go to the file react-dom.development.js
, located on the npm package react-dom
.
- First, on line 3, the
render()
function can receive three parameters: element, container and, callback. - Then, on line 4 the function will make a validation, where it will check if the
document.getElementById(‘app’)
argument that we passed is a element, document, document fragment or comment node. - After this, it will validate if the
container
argument that we passed was previously passed toReactDOM.createRoot()
, which is not supported. - Last, after these validations, it will return the function
legacyRenderSubtreeIntoContainer
with the parameters:
parentComponent, children, container, forceHydrate, callback
set to:
null, <MyComponent />, document.getElementById(‘app’), false, callback
5. Next, the program will call the function, legacyRenderSubtreeIntoContainer
where it modifies the children of the container. Here it will also insert a component to an existing DOM node without overwriting the existing children, if needed.
6. Next, the updateContainer
function will be called and, if the React element was previously rendered into container
, this will perform an update on it and only mutate the DOM as necessary to reflect the latest React element.
7. If the optional callback is provided, it will be executed after the component is rendered or updated.
8. Finally, the function will return a reference to the root ReactComponent
instance.
Did I miss anything? Please don’t hesitate to contact me Alejandra Bricio.
Happy coding!