DEV Community

Linas Spukas
Linas Spukas

Posted on

React Work Phases

To make a great user experience updating the page, React split its internal processes into two phases: "render" and "commit". Both phases run synchronously and make sure, that user sees already calculated styles, layout and updated UI.

Render Phase

When the time comes to render a page, usually caused by a change of component's state or props, React does a process, called reconciliation.
First, it creates a virtual DOM by recursively calling components render functions down the tree until all React elements are returned. Second, it compares that virtual DOM with the last render looking for differences. If there is a change then it updates the DOM.

This is a slower process comparing to the "commit" phase. Because when comparing the next render with the previous, React checks if element types and order are the same. If element types are the same, then the same element instances in the DOM will be used. Same goes for the order, if it changed, then the sub-tree of elements will be recreated. To tell React that it is the same elements regardless of the order we are giving unique "key" attributes for components.

The following lifecycle methods are called during the render phase:

  • componentWillMount
  • componentWillReceiveProps
  • componentWillUpdate
  • getDerivedStateFromProps
  • shouldComponentUpdate

These methods can be called even a couple of times during the render phase (because of errors or interruptions), so it is important to not have side-effects, like changing the UI or calling external services, to avoid problems and memory leaks.

Commit Phase

This is a second and fast phase where React applies changes. Now that render phase produced result how the DOM should look like, commit phase inserts new, updates existing or removes unnecessary DOM nodes.

During this process, the following lifecycle methods are called:

  • componentDidMount
  • componentDidUpdate
  • componentWillUnmount
  • componentDidCatch

These methods are called only once and side effects are permitted. If the state or view changes as a side-effect, the render phase will be triggered safely again.

Summing Up

React works in two phases, render and commit. During the render phase, it calls a render method and performs a comparison to the previous render. And the commit phase is where the changes are directly applied to the DOM. After that, the webpage is updated and presented to the user.

Top comments (1)

otienosteve profile image

I had quite a problem trying to grasp this concept on the React Documentation _ Mutations, subscriptions, timers, logging, and other side effects are not allowed inside the main body of a function component (referred to as React’s render phase). Doing so will lead to confusing bugs and inconsistencies in the UI._
But after this post it makes a lot of sense. Thanks Linas