How render works

How render works

The first time that your application calls ReactDOM.render(), the outcome is pretty simple. React just walks through the supplied ReactElement and creates corresponding DOM Nodes under the root node that you passed in.

But the second and subsequent calls are different. They don’t modify previously rendered DOM Nodes unless the corresponding ReactElement objects have changed.

React is pretty clever about reusing DOM nodes instead of replacing them. In fact, if you call render twice with the same element, nothing changes.

var rootElement = React.createElement(App, data)

ReactDOM.render(rootElement, document.getElementById('root'))

// This call to render does nothing, as the rendered element hasn't
// changed from the previous one.
ReactDOM.render(rootElement, document.getElementById('root'))

#React’s reconciliation algorithm

The process that React uses to decide what to re-render — and what to keep the same — is called reconciliation.

During reconciliation, React recursively compares the new ReactElement with the previous one. It uses a number of rules to decide what to do:

  • Elements with differing types are disposed and re-rendered
  • Elements with differing props or children are re-rendered in place
  • Identical elements which have been re-ordered within an array are moved to reflect the new order

While it’s important to know that these rules exist, you’ll find that when you’re writing React code, things just work as expected. That’s the beauty of React.

However, there is one catch. When React encounters an array of elements with identical type and props, despite looking identical from the outside, it cannot know that they are really identical. And this is why you sometimes need to set a key.

Progress to next section.