Logo
READLEARNKNOWCONNECT
Back to Lessons

    Page

  • - What is JSX?
  • - JSX Rules You Must Know
  • - What is the Virtual DOM?
  • - How It Works
  • - Mini Project Step

3. Understanding JSX and the Virtual DOM

Level: BeginnerDuration: 18m

What is JSX?

JSX (JavaScript XML) lets us write HTML-like syntax inside JavaScript. React uses JSX to make UI code cleaner and more readable. It’s not required to use React, but trust me, you’ll love how natural it feels.

jsx
const element = <h1>Hello, React!</h1>;

Behind the scenes, this JSX gets converted to JavaScript using React.createElement.

javascript
const element = React.createElement('h1', null, 'Hello, React!');

JSX Rules You Must Know

  • JSX must return a single parent element.
  • Use curly braces {} to embed JavaScript expressions.
  • Class names use `className` instead of `class`.
  • JSX must be compiled (handled automatically by Vite).
jsx
function Welcome() {
  const name = "Chrise";
  return (
    <div>
      <h2>Hello, {name}</h2>
      <p>Let's learn JSX together.</p>
    </div>
  );
}

What is the Virtual DOM?

The Virtual DOM is a lightweight copy of the real DOM. Instead of updating the actual webpage for every tiny change (which is slow), React updates the Virtual DOM first, calculates what changed, and applies only the necessary updates to the real DOM.

This process makes React fast and efficient, especially in large apps.

How It Works

  • You interact with the UI (like clicking a button).
  • React updates the Virtual DOM.
  • React compares it to the previous version (this is called diffing).
  • Only the changed parts are updated in the real DOM.
jsx
import { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <button onClick={() => setCount(count + 1)}>
      Count: {count}
    </button>
  );
}

When you click the button, React only updates the number inside it—not the whole page.

Mini Project Step

Update your `App.jsx` file to return JSX and add a simple Virtual DOM interaction using a button.

jsx
import { useState } from 'react';

function App() {
  const [name, setName] = useState("React Developer");

  return (
    <div>
      <h1>Hello, {name} 👋</h1>
      <button onClick={() => setName("Future React Pro")}>Change Name</button>
    </div>
  );
}

export default App;