What is React Render?
Here is a simple React component
const MyComponent = () => {
const [counter, setCounter] = useState(0)
return <p>{counter}</p>
}
When we update the counter, the component re-renders, and, as a result, the DOM gets updated in the browser. Click Update to see it for yourself π
My Component
statecounter: 0
return <p>{counter}</p>
DOM
<p>0</p>
Let's slightly alter our component, and instead of returning {counter} we return a simple string - Hello World. Now, when we update the counter, the component re-renders, but the resulting DOM remains the same. Try it yourself π
My Component
statecounter: 0
return <p>Hello World</p>
DOM
<p>Hello World</p>
As we can see, Component Render β DOM update. When we say react renders a component, it simply means that react calls this component as a function. In our case MyComponent(). To understand this better, let's check how React rendering mechanism works.
React Rendering Mechanism Works in 3 Steps
- Triggering a render. Something triggers a rendering process. It can either be the initial render or a consequential state update.
- Rendering a component. React renders a component by calling the component function and receiving the resulting JSX.
- Commit. React compares the previously saved JSX to the newly received one and carefully updates only those parts of the DOM that require changes.
Let's see how it works step by step:
My Component
statecounter:0
return <p>{counter}</p>
DOM
<p>0</p>
Move the slider to see the rendering process π
And now, with βHello World.β
My Component
statecounter:0
return <p>Hello World</p>
DOM
Hello World
Move the slider to see the rendering process π
Two examples above demonstrate the rendering process during a state update. But every component also has to render the first time when it mounts before we update any state. It's called the initial render. The same rendering rules apply to this render as well.
My Component
statecounter: 0
return <p>{counter}</p>
DOM
<p>0</p>
Move the slider to see the rendering process π
Summary
- React render β DOM update
- React render is just a function call
- React rendering mechanism works in 3 steps - trigger, render, commit.
- React only updates parts of the DOM that require changes