React: Introduction to React
React is a JavaScript library for building user interfaces. If we compare a web page to a house, HTML is the brick walls, CSS is the interior design, and JavaScript is the electrical and plumbing systems; then React is a prefabricated assembly system—it lets you design each room (component) independently and then assemble them into a complete building.
1. What You'll Learn
- What is React, and why do we need it?
- Declarative Programming vs. Imperative Programming
- How the Virtual DOM Works
- React vs Vue vs Angular
- An Overview of the React Ecosystem
2. A True Story of a Front-End Developer
(1) Pain Point: One page, 30,000 lines of jQuery
Alice works as a front-end developer at a medium-sized e-commerce company. The company has an admin dashboard that was built using jQuery over the course of three years and has accumulated over 30,000 lines of code.
▶ Example: Introduction to React
Output:
Console output displays the results of the logged values
// A typical product list page — jQuery code
function updateProductList(category) {
// Manual DOM operation
$('#product-list').empty()
$('#loading-spinner').show()
$.get('/api/products?category=' + category, function(data) {
$('#loading-spinner').hide()
data.forEach(function(product) {
// Concatenate HTML strings line by line
var html = '<div class="product-card">' +
'<h3>' + product.name + '</h3>' +
'<p>' + product.price + '</p>' +
'<button onclick="addToCart(' + product.id + ')">Add to Cart</button>' +
'</div>'
$('#product-list').append(html)
})
})
}
Output:
Console output displays the results of the logged values
The problem with this page is:
- State and DOM are out of sync: When the shopping cart total changes, the numbers in the other three places on the page need to be updated manually.
- Poor maintainability: Modifying a single feature may require changes to five files
- Performance Issues: Each update directly manipulates the actual DOM, causing frequent reflows and repaints on the page
(2) React's Approach: Declarative + Component-Based
Rewriting the same logic using React:
function ProductList({ category }) {
const [products, setProducts] = React.useState([])
const [loading, setLoading] = React.useState(true)
React.useEffect(() => {
fetch('/api/products?category=' + category)
.then(res => res.json())
.then(data => {
setProducts(data)
setLoading(false)
})
}, [category])
if (loading) return <Spinner />
return (
<div className="product-grid">
{products.map(product => (
<ProductCard key={product.id} product={product} />
))}
</div>
)
}
Benefits: 70% reduction in code size, automatic state synchronization, changes to one component do not affect others, and a 5x performance boost (batch updates of the virtual DOM).
3. Core Concepts of React
(1) Declarative Programming vs. Imperative Programming
| Dimension | Imperative (jQuery) | Declarative (React) |
|---|---|---|
| Focus | How to do it (step-by-step DOM ops) | What to do (description of final state) |
| Code style | Step-by-step | Descriptive declaration |
| State Management | Manual state + manual DOM update | State auto-mapped to UI |
| Debugging difficulty | Requires tracking every DOM operation | Only requires monitoring state changes |
// Imperative: tell the browser what to do at each step
const div = document.createElement('div')
div.className = 'alert'
div.textContent = 'Hello'
document.body.appendChild(div)
// Declarative: tell React what result you want
function Alert({ message }) {
return <div className="alert">{message}</div>
}
// React automatically creates and updates the DOM
(2) Virtual DOM
The virtual DOM is a core technology for React performance optimization. It is not a real DOM tree, but rather a lightweight JavaScript object tree.
graph TB
A[State changes] --> B[Create a new virtual DOM tree]
B --> C[Diff A Comparison of Old and New Virtual Environments DOM]
C --> D[Compute minimum update operations]
D --> E[Batch update real DOM]
E --> F[Page update complete]
style A fill:#ff6b6b,color:#fff
style C fill:#4ecdc4,color:#fff
style E fill:#45b7d1,color:#fff
| Concept | Real DOM | Virtual DOM |
|---|---|---|
| Essence | Native browser objects | Regular JavaScript objects |
| Creation cost | High (requires browser layout) | Very low (pure JS operations) |
| Update método | Direct operation, triggers reflow/repaint | Batch update after diff |
| Update granularity | Single operation | Batch minimal update |
(3) Component-Based Development
The core idea behind React is to break down a page into independent, reusable components, with each component responsible only for its own specific area.
| Concept | Analogy | Explanation |
|---|---|---|
| Component | LEGO brick | Each component is an independent functional unit |
| Props | Block color/size | Parameters passed from the parent component to the child component |
| State | Block state (new/old) | Data managed internally by the component |
| Component tree | Assembled LEGO model | Components nested to form a page |
// Component-based: page broken into independent components
function Page() {
return (
<div>
<Header /> {/* Header navigation */}
<Sidebar /> {/* Sidebar */}
<MainContent /> {/* Main content area */}
<Footer /> {/* Footer copyright */}
</div>
)
}
4. React vs. Other Popular Frameworks
| Dimension | React | Vue | Angular |
|---|---|---|---|
| Developer | Meta (Facebook) | You Yuxi (Individual) | |
| First released | 2013 | 2014 | 2010 |
| Type | UI Library | Progressive Framework | Full-Featured Framework |
| Template Syntax | JSX (HTML embedded in JavaScript) | HTML templates + directives | TypeScript + decorators |
| Data Flow | Unidirectional (top-down) | Two-way binding (v-model) | Two-way binding |
| State Management | Community Solutions (Redux/Zustand) | Official Pinia/Vuex | Official RxJS + Services |
| Learning Curve | Moderate (requires understanding of JSX + Hooks) | Low (template-friendly) | High (TypeScript + dependency injection) |
| SSR Solution | Next.js | Nuxt | Angular Universal |
| Use Cases | Large-scale SPAs, mobile apps (React Native) | Small and medium-sized projects, rapid prototyping | Large-scale enterprise applications |
| GitHub ⭐ | 230k+ | 220k+ | 100k+ |
| Job Market (China) | High (mostly in first-tier cities) | High (mostly in small and medium-sized enterprises) | Moderate (foreign companies/large tech firms) |
Summary: React is suitable for projects that require high control, high component reusability, and cross-platform support (Web + mobile). Vue is easier to get started with and is suitable for rapid iteration. Angular is suitable for large enterprise-level teams.
5. Overview of the React Ecosystem
React is not an "all-in-one" framework, but rather a flexible UI library. It relies on the community ecosystem to provide features such as routing, state management, and build tools.
| Field | Core Tools | Description |
|---|---|---|
| Build Tools | Vite (Recommended) / Create React App | Project Scaffolding and Development Server |
| Routing | React Router v6 / TanStack Router | Page navigation and URL management |
| State Management | State / Redux Toolkit / Context API | Global Data Management |
| Data Retrieval | TanStack Query (React Query) / SWR | Server-side Data Caching and Synchronization |
| Styling | Tailwind CSS / CSS Modules / styled-components | Component Styling |
| Testing | Vitest + React Testing Library / Playwright | Unit testing and E2E testing |
| SSR/SSG | Next.js | Server-side rendering and static generation |
| Mobile | React Native | Building Native Mobile Apps with React |
| Animation | Framer Motion / React Spring | UI animations and transitions |
| Component Libraries | Ant Design / MUI / Shadcn/ui | Out-of-the-box UI components |
graph LR
A[React] --> B[Build: Vite]
A --> C[Routing: React Router]
A --> D[Status: Zustand/Redux]
A --> E[Data: TanStack Query]
A --> F[Style: Tailwind/CSS Modules]
A --> G[Test: Vitest + RTL]
A --> H[SSR: Next.js]
A --> I[Mobile: React Native]
style A fill:#61dafb,color:#000
style H fill:#000,color:#fff
style I fill:#61dafb,color:#000
6. Complete Example: Building a Simple "Like" Button with React
// ============================================
// Example:use React Build a "Like" Button
// Features:Demonstrating Declarative Programming + Component-based + Core Concepts of State Management
// ============================================
import React from 'react'
import { createRoot } from 'react-dom/cliente'
// 1. Define a "Like" button component
function LikeButton() {
// Usage useState Manage Like Status
const [liked, setLiked] = React.useState(false)
const [count, setCount] = React.useState(0)
// Handling Click Events
function handleClick() {
if (liked) {
setLiked(false)
setCount(count - 1)
} else {
setLiked(true)
setCount(count + 1)
}
}
// Declarative UI:Render different appearances based on state
return (
<button
onClick={handleClick}
style={{
padding: '10px 20px',
fontSize: '16px',
backgroundColor: liked ? '#ff4757' : '#f1f2f6',
color: liked ? '#fff' : '#333',
border: 'none',
borderRadius: '5px',
cursor: 'pointer'
}}
>
{liked ? '❤️ Liked' : '🤍 Like'} ({count})
</button>
)
}
// 2. Add components to the page
function App() {
return (
<div style={{ textAlign: 'center', padding: '50px' }}>
<h1>React Examples of Likes</h1>
<p>Click the button to experience declarative programming UI:Just keep an eye on the state,No action required DOM</p>
<LikeButton />
<LikeButton /> {/* Component Reusability!*/}
</div>
)
}
// 3. Render to page
const root = createRoot(document.getElementById('root'))
root.render(<App />)
What does this example demonstrate?
- Declarative: We simply describe "what the button should look like when the like status changes," and React automatically updates the DOM
- Component-based:
LikeButtonis an independent component that can be reused multiple times- State Management:
likedandcountare automatically tracked by React; no manual DOM manipulation is required
▶ Example 2: Visualization of the React component tree
Output:
Displays: "' + '". Button: Add to Cart
// ============================================
// Example:use React The component tree displays the page structure
// Features:Simulate the component tree of a blog homepage,Demonstrating a Component-Based Approach
// ============================================
// Leaf Component:Article Card
function ArticleCard({ title, excerpt }) {
return (
<div style={{ border: '1px solid #eee', borderRadius: '8px', padding: '12px', marginBottom: '12px' }}>
<h3 style={{ margin: '0 0 8px 0' }}>{title}</h3>
<p style={{ color: '#666', margin: 0, fontSize: '14px' }}>{excerpt}</p>
</div>
)
}
// Composite Components:List of Articles
function ArticleList({ articles }) {
return (
<div>
<h2>Latest Articles</h2>
{articles.map(article => (
<ArticleCard key={article.id} title={article.title} excerpt={article.excerpt} />
))}
</div>
)
}
// Composite Components:Sidebar
function Sidebar() {
return (
<div style={{ backgroundColor: '#fafafa', padding: '16px', borderRadius: '8px' }}>
<h3>Categories</h3>
<ul style={{ listStyle: 'none', padding: 0 }}>
<li>React Tutorial (12)</li>
<li>TypeScript (8)</li>
<li>Node.js (5)</li>
</ul>
</div>
)
}
// Root Component:Blog Home
function BlogHome() {
const articles = [
{ id: 1, title: 'React Getting Started Guide', excerpt: 'Study React Core Concepts and Best Practices...' },
{ id: 2, title: 'Understanding the Virtual DOM', excerpt: 'Virtual DOM How to Improve React Application Performance...' },
{ id: 3, title: 'Component Design Patterns', excerpt: 'Master React Techniques for Combining and Reusing Components...' }
]
return (
<div style={{ maxWidth: '960px', margin: '0 auto', padding: '20px' }}>
<header style={{ textAlign: 'center', marginBottom: '24px' }}>
<h1>📝 My Tech Blog</h1>
<nav>
<a href="#" style={{ margin: '0 12px' }}>Home</a>
<a href="#" style={{ margin: '0 12px' }}>About</a>
<a href="#" style={{ margin: '0 12px' }}>Contact</a>
</nav>
</header>
<div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: '24px' }}>
<ArticleList articles={articles} />
<Sidebar />
</div>
<footer style={{ textAlign: 'center', marginTop: '24px', color: '#999', fontSize: '13px' }}>
<p>© 2026 web-tutorial.com</p>
</footer>
</div>
)
}
// Component tree Structure:
// BlogHome
// ├── header (Navigation Bar)
// └── div.grid
// ├── ArticleList
// │ ├── ArticleCard × 3
// └── Sidebar
// └── Category List
Output:
Blog homepage: header "📝 My Tech Blog" with nav, 3 article cards (React Getting Started Guide, Understanding the Virtual DOM, Component Design Patterns), sidebar with categories, footer "© 2026 web-tutorial.com"
❓ FAQ
use() hook, Server Components, and Actions). For production environments, we recommend starting with React 18 and upgrading once the React 19 ecosystem has matured.📖 Summary
- React is a UI library that uses declarative programming—you describe the result you want, and React handles updating the DOM
- Virtual DOM is at the heart of React's performance: it compares a tree of JavaScript objects to update the actual DOM in batches.
- Component-based architecture is React’s most fundamental design principle—each component is independent, reusable, and responsible only for its own logic.
- React is suitable for large-scale SPAs and cross-platform development; it has a moderate learning curve (requires a basic understanding of JavaScript).
- The React ecosystem is rich but not restrictive; you are free to choose your own routing, state management, and build tools.
📝 Exercises
- Basic Question (Difficulty: ⭐): Go to react.dev, find the "Learn React" section on the homepage, browse through the first three tutorial pages, and write down the three concepts you think are most important.
- Thinking Question (Difficulty: ⭐): Explain in your own words the difference between "declarative programming" and "imperative programming," and give an example from everyday life (not limited to programming).
- Comparison Question (Difficulty: ⭐⭐): If you wanted to build a blog website, which would you think is more suitable: React or Vue? List at least two reasons to support your choice.