DEV Community

vijayaragavan nandhagopal
vijayaragavan nandhagopal

Posted on

How React works?

1. Component is the base

  • React app is made of components.
  • A component is just a JavaScript function that returns UI.
function App() {
  return <h1>Hello</h1>
}

Enter fullscreen mode Exit fullscreen mode

2. JSX (JavaScript XML)

  • JSX looks like HTML but it’s not HTML.
  • React converts JSX into JavaScript objects.
<h1>Hello</h1>

React.createElement("h1", null, "Hello")

Enter fullscreen mode Exit fullscreen mode

3. Virtual DOM

  • React creates a Virtual DOM, this is lightweight javascript object copy of real DOM.
  • Think of it as a blueprint, not the real building.
Initial render:
JSX → Virtual DOM → Real DOM

State change:
JSX → New Virtual DOM
        ↓
Compare with Old Virtual DOM
        ↓
Find differences
        ↓
Update ONLY required parts in Real DOM

Enter fullscreen mode Exit fullscreen mode
  • At first, React converts JSX into a Virtual DOM and uses it to create the Real DOM, so the UI appears on the screen.
  • When a state change happens React does not touch the Real DOM immediately. Instead, it re-runs the component and generates a new Virtual DOM based on the updated state.
  • React then compares the new Virtual DOM with the old Virtual DOM using its diffing (reconciliation) algorithm to identify exactly what has changed.
  • After finding these differences, React updates only the affected parts of the Real DOM, not the entire page.

Top comments (0)