⚛️ What is React and Why Use It?
For three weeks you've built pages by hand — grabbing elements, wiring events, and rewriting the DOM whenever data changed. It worked, but it got tangled fast. React flips the model: you describe what the screen should look like for a given set of data, and React does the tedious work of keeping the real page in sync. This lesson is your first look at that idea and why it took over front-end development.
Week 4 · Monday: React Fundamentals · Lecture 1
🎯 Learning Objectives
By the end of this lesson, you will be able to:
- Explain what React is and the specific UI problem it was built to solve
- Contrast imperative DOM manipulation with React's declarative approach
- Describe the Virtual DOM and reconciliation in plain language
- Identify the four core ideas: components, JSX, props, and state
- Decide when React is a good fit — and when it is overkill
- Scaffold a new React project with Vite and read its starting files
Estimated Time: 55 minutes
Practice: Rewrite an imperative counter as a declarative React component and scaffold a Vite app.
In This Lesson
What is React?
React is an open-source JavaScript library for building user interfaces, created at Facebook (now Meta) in 2013 and maintained today by Meta and a huge open-source community. Notice the word library, not framework: React focuses narrowly on rendering UI, and you assemble the rest of your stack (routing, data fetching, build tools) from complementary pieces.
The clearest analogy is a LEGO set. Instead of sculpting a whole scene from one block of clay, you snap together small, self-contained bricks — a button here, a card there — and reuse them everywhere. In React those bricks are called components, and an entire application is just components nested inside components.
The reason React matters is not that it draws HTML — plain JavaScript already does that. It matters because it makes keeping the UI in sync with your data dramatically simpler. That is the whole game, and the next section shows exactly why the old way hurt.
Imperative vs. Declarative
Imagine a restaurant menu board. In the imperative style you are the person who must personally walk up, erase a price, and rewrite it by hand every single time anything changes — and you have to remember exactly which letters to erase. In the declarative style you simply hand over the new menu data and say "make the board match this," and someone else figures out the smallest set of changes.
The imperative way (manual DOM updates)
Here is the pattern you have used so far — you tell the browser step by step how to update the page:
// Imperative: YOU manage every DOM change by hand
const board = document.getElementById('menu');
let dishes = [
{ name: 'Pizza', price: 12 },
{ name: 'Pasta', price: 10 },
{ name: 'Salad', price: 8 },
];
function renderMenu() {
board.innerHTML = ''; // wipe everything
for (const dish of dishes) {
const row = document.createElement('div');
row.textContent = `${dish.name}: $${dish.price}`;
board.appendChild(row); // rebuild everything
}
}
// One price changes → we blow away and rebuild the WHOLE list
dishes = dishes.map(d => d.name === 'Pizza' ? { ...d, price: 13 } : d);
renderMenu();
As a page grows, this bookkeeping explodes. Every feature has to remember which nodes to create, update, and delete, and small mistakes leave the screen out of sync with your data.
The declarative way (describe the result)
In React you write a function that returns what the UI should look like for the current data. When the data changes, you update the data and React re-runs your description and patches the page for you:
// Declarative: describe WHAT the UI is, not HOW to mutate it
import { useState } from 'react';
function Menu() {
const [dishes, setDishes] = useState([
{ name: 'Pizza', price: 12 },
{ name: 'Pasta', price: 10 },
{ name: 'Salad', price: 8 },
]);
function raisePizza() {
// Update the DATA; React updates the screen
setDishes(dishes.map(d =>
d.name === 'Pizza' ? { ...d, price: 13 } : d
));
}
return (
<div>
{dishes.map(dish => (
<div key={dish.name}>{dish.name}: ${dish.price}</div>
))}
<button onClick={raisePizza}>Raise pizza price</button>
</div>
);
}
📖 The mental shift
Imperative code answers "what steps do I take?" Declarative code answers "what should the result be?" React turns your data into UI, so you stop babysitting the DOM and start thinking about state. This single shift is why React scales to enormous apps.
The Virtual DOM
If React re-runs your whole component every time data changes, wouldn't rebuilding the page constantly be slow? It would — if React touched the real DOM directly. Instead it keeps a lightweight in-memory copy of the UI called the Virtual DOM.
Think of it as an architect's blueprint. When something changes, React draws a fresh blueprint, compares it to the previous one (a process called reconciliation or "diffing"), and then makes only the handful of real-world changes that actually differ. The expensive part — touching the real browser DOM — is kept to the bare minimum.
💡 You don't call the Virtual DOM
The Virtual DOM is React's internal machinery, not an API you use. You never write diffing code — you just describe your UI and update state. Understanding it, though, explains why the declarative model is fast enough for real apps.
The Four Core Ideas
Nearly everything in React is built from four concepts. You'll spend the rest of this week on each one — here is the map so the pieces have somewhere to land.
1. Components
A component is a JavaScript function that returns UI. In modern React, components are functions (we use hooks for everything the old class syntax did). Name them with a capital letter so React knows they are components, not plain HTML tags.
// A component is just a function that returns JSX
function Welcome(props) {
return <h1>Hello, {props.name}!</h1>;
}
// Use it like a custom HTML tag:
<Welcome name="Sarah" />
2. JSX
That HTML-looking syntax inside the function is JSX — a convenience that lets you write markup right in JavaScript. A build tool compiles it into plain function calls before it reaches the browser. You'll study JSX in the very next lesson.
const element = <h1 className="greeting">Hello, world!</h1>;
// A build step turns that into a plain function call:
// React.createElement('h1', { className: 'greeting' }, 'Hello, world!')
3. Props
Props are the inputs you pass into a component, like arguments to a function. They flow down from parent to child and are read-only — a child never rewrites the props it was handed.
function Recipe({ name, prepTime }) {
return (
<div className="recipe">
<h2>{name}</h2>
<p>Prep time: {prepTime} min</p>
</div>
);
}
// Parent passes data down via props:
<Recipe name="Pancakes" prepTime={15} />
4. State
State is data a component owns and can change over time — the current count, whether a menu is open, the text in a form. When state changes, React re-renders the component. You create it with the useState hook (studied later this week).
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0); // state starts at 0
return (
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}
✅ One direction of data
Data flows down through props and events flow up through callbacks. This "unidirectional data flow" is what makes React apps predictable: to find where a value comes from, you follow it upward to the component that owns the state.
When to Use React
React shines when a UI is interactive and data-driven — where the screen must constantly reflect changing state. It is a fantastic default for:
- Single-page applications (SPAs): Gmail-style apps that update without full page reloads
- Complex, stateful UIs: dashboards, admin panels, builders, editors
- Real-time interfaces: chat, live feeds, collaborative tools
- Design systems: a shared library of reusable components across many pages
- Cross-platform reach: the same mental model powers React Native for mobile
Real products lean on it heavily: Facebook, Instagram, Netflix, Airbnb, and countless dashboards. But React is not a law of nature — reach for something lighter when the job is simpler:
⚠️ When React is overkill
A mostly-static marketing page, a blog, or a small widget rarely needs React's runtime and build tooling. Plain HTML/CSS with a sprinkle of vanilla JavaScript, or a static-site generator, may load faster and be simpler to maintain. Choose React when interactivity and shared state are the hard part — not just to have it on the résumé.
Getting Started with Vite
The modern, recommended way to start a React project is Vite — a fast build tool that gives you an instant dev server and hot reloading. (You may still see the older create-react-app in tutorials; it is no longer actively recommended.) From your terminal:
# Scaffold a new React project with Vite
npm create vite@latest my-react-app -- --template react
cd my-react-app
npm install # download dependencies
npm run dev # start the dev server at http://localhost:5173
Open the printed URL and you'll see a starter page that live-updates as you edit. The heart of the app is src/App.jsx:
// src/App.jsx — your first component
import { useState } from 'react';
function App() {
const [message, setMessage] = useState('Welcome to React!');
return (
<div className="App">
<h1>{message}</h1>
<button onClick={() => setMessage('You clicked the button!')}>
Click Me
</button>
</div>
);
}
export default App;
What you'll see
A heading reading "Welcome to React!"
Click the button → the heading changes to "You clicked the button!"
No page reload, no manual DOM code.
Notice how much this file already uses: a component (App), JSX (the markup), and state (message). The rest of Week 4 fills in the details.
Practice & Quiz
🏋️ Exercise 1: Imperative → declarative
Goal: Take this imperative counter and rewrite it as a declarative React component.
// Imperative version to convert:
let count = 0;
const btn = document.getElementById('btn');
btn.addEventListener('click', () => {
count++;
btn.textContent = `Clicked ${count} times`;
});
💡 Hint
Store count in useState. Put the display text right in the JSX, and update state in the onClick handler instead of touching textContent.
✅ Solution
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}
No DOM lookups, no manual text updates — you changed state and React redrew the button.
🏋️ Exercise 2: Scaffold and edit
Goal: Create a real project and make it yours.
- Run the Vite command above to scaffold
my-react-app. - Start the dev server and open the URL.
- In
src/App.jsx, change the heading text and add a second button that resets the message. Watch it hot-reload.
✅ Solution sketch
function App() {
const [message, setMessage] = useState('Hello from my first app!');
return (
<div className="App">
<h1>{message}</h1>
<button onClick={() => setMessage('Clicked!')}>Click</button>
<button onClick={() => setMessage('Hello from my first app!')}>Reset</button>
</div>
);
}
🎯 Quick Quiz
Question 1: React's approach to building UI is best described as:
Question 2: What is the main purpose of the Virtual DOM?
Question 3: In React, data typically flows…
Best Practices & Pitfalls
✅ Do
- Think in terms of state → UI: change the data and let React render
- Start new projects with Vite and modern function components + hooks
- Name components with a capital letter (
UserCard, notuserCard) - Reach for React when interactivity and shared state are the hard part
❌ Don't
- Mix manual
document.querySelectorDOM edits into React components - Start from class components — modern React is function components and hooks
- Reach for
create-react-appin 2024+ — it's no longer recommended - Add React to a purely static page just because it's popular
⚠️ It's a library, not a framework
React deliberately handles only the view layer. Routing, data fetching, and global state come from separate packages (or a meta-framework like Next.js). That flexibility is a feature — but it means you'll assemble a small toolkit as your apps grow.
Summary
🎉 Key Takeaways
- React is a component-based library for building user interfaces, made at Meta
- Its superpower is being declarative: you describe the UI for your data, React syncs the DOM
- The Virtual DOM makes that fast by diffing and patching only what changed
- Everything is built from components, JSX, props, and state
- Data flows down via props, up via events — predictable, one-directional
- Start modern projects with Vite and function components
📚 Additional Resources
- react.dev — Quick Start (official)
- react.dev — Thinking in React
- react.dev — Start a New React Project
🚀 What's Next?
You've met JSX in passing — that HTML-in-JavaScript syntax inside every component. Next we take it apart properly: the rules that make JSX different from HTML, how to embed JavaScript with curly braces, and the gotchas that trip up every beginner. On to JSX Syntax.
🎉 Welcome to React!
You now understand the idea the whole rest of this module builds on. Everything from here is filling in the details of components, JSX, props, and state.