Now that we know how to use React, let's take a quick look at how React works.
React uses a concept called the virtual DOM. When you write
<div>, you are not immediately creating a div. Instead, you are working with the virtual DOM, a representation of the actual DOM. I like to think of virtual DOM components as markers; they tell React what should be rendered. It is then the React engine's job to make sure the actual DOM matches the given markers.
With this approach, React gets to choose how to update the actual DOM. This allows for performance optimizations such as batching and minifying DOM updates.
You may be surprised that React calls render everytime a component's state changes, as well as the render of all its children components. Traditionally, when you want to make a red button blue, you write code along the lines of
$(button).removeClass('red').addClass('blue'). This is an imperative style of programming. With React, you modify a component's state and the component tree rerenders. This is a more declarative style of programming.
When React rerenders, now it has two component trees, one from before the rerender, and one after. Let's do a little exercise. Pretend you are the React engine and you were told to render the following.
<ul className="list"> <li>A</li> <li>B</li> <li>C</li> </ul>
Then, you were told to render the following in the same place.
<ul className="list"> <li>A</li> <li>B</li> <li className="selected">C</li> </ul>
What would you do? You wouldn't throw away all the old contents. The only change you would make is add the class "selected".
This is what React does at a high level. It does a "diff" between two render passes and applies the minimal changes needed to reflect the new render tree. If this feels magical, we'll break this down in other articles on the site.
This is the end of the React basics tutorial. Now you have the knowledge you need to start building your React applications!
Want an easy way to make your images a little more graceful? This recipe is for an Image component that fades in once the image is loaded. You can see it in action here.