I recently completed a mock technical interview with Skilled Inc. to test my React knowledge. Though I scored a 4/5 and earned generally favorable remarks, my interviewer suggested a deeper dive into how JSX and the Virtual DOM actually work. Not just what they are, but how they are. I understood the higher-level concepts and answered all of his basic inquiries, but he caught me on this “gotcha” question: “Where does the Virtual DOM live?”
Don’t know the answer, either? Don’t fret—just keep on reading. This blog’s for you!
const bestSportsTeam = <p>Carolina Panthers, duh.<p>return (
The result is the following, rendered to the (actual) DOM.
Carolina Panthers, duh.
const bestSportsTeam = React.createElement(
'Carolina Panthers, duh.'
The Virtual DOM
The DOM, which stands for Document Object Model, is a tree data structure that controls what’s rendered on a user’s screen. It’s the UI representation of an app in a browser. Each element is a node in the tree.
How? The Virtual DOM—which lives in memory, by the way, to answer the question in the intro—serves as a lightweight copy of the real DOM. It’s a representational version that lacks the power to actually manipulate what’s on the screen. When you change an application’s state, React produces two depictions of the Virtual DOM: one that represents the DOM tree pre-update, and one which represents the DOM tree post-update. React then runs an algorithm that compares the two versions and logs the changes, a process called diffing.
Finally, in one last task known as reconciliation, the ReactDOM library syncs the new version of the Virtual DOM with the actual DOM, updating what’s displayed on the screen. In our example of the Carolina Panthers roster, only the effected list items would get re-rendered, and not the entire list.
- Accomplished through a series of React.createElement() calls.
- An application’s state changes.
- React creates a new version of the Virtual DOM and compares the pre-update Virtual DOM with the post-update Virtual DOM (diffing).
- Only the elements that were changed are updated on the actual DOM through the ReactDOM library (reconciliation).
- The browser updates and the new application state is displayed on the screen.