EasyConcept

What is the virtual DOM in React and how does it work?

Technology:
React
Experience:
Intern,
Junior

Quick answer

The virtual DOM is a lightweight JavaScript copy of the UI that React compares with the previous version after each update, so it only changes the parts of the real DOM that actually differ.

Detailed explanation

When state or props change, React re-runs your component to produce a new tree of React elements (the virtual DOM). It then compares that tree with the previous one in a process called reconciliation, works out the minimal set of changes, and applies only those to the real DOM.

Touching the real DOM is comparatively expensive, and batching updates lets React do it once per update instead of once per change. The virtual DOM is not automatically faster than hand-written DOM code, but it gives you a declarative model: you describe what the UI should look like for the current state, and React figures out how to get there.

Key points

  • Virtual DOM = tree of plain objects describing the UI
  • Reconciliation compares old and new trees (diffing)
  • Only the differences are applied to the real DOM

Follow-up questions

  • What is reconciliation?
  • What is React Fiber?
  • ReactEasy

    Why do we need keys in React lists?

    Keys give each list item a stable identity so React can match items between renders and correctly add, remove or reorder them without recreating or mixing up their state.

    Junior 路 Mid-level 路 Performance
  • ReactMedium

    What is the difference between SSR, SSG and CSR in React?

    CSR renders in the browser after JavaScript loads, SSR renders the HTML on the server for each request, and SSG renders the HTML once at build time; SSR and SSG give crawlers and users content faster, which helps SEO.

    Mid-level 路 Senior 路 Performance
  • ReactEasy

    What is the difference between props and state in React?

    Props are read-only inputs passed from a parent component, while state is data a component owns and can change over time, which triggers a re-render when updated.

    Intern 路 Junior 路 State Management