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



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:

TEXT
Console output displays the results of the logged values
JAVASCRIPT
// 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:

TEXT
Console output displays the results of the logged values

The problem with this page is:

(2) React's Approach: Declarative + Component-Based

Rewriting the same logic using React:

JSX
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>
  )
}
▶ Try it Yourself

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
JAVASCRIPT
// 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.

100%
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
JSX
// Component-based: page broken into independent components
function Page() {
  return (
    <div>
      <Header />        {/* Header navigation */}
      <Sidebar />       {/* Sidebar */}
      <MainContent />   {/* Main content area */}
      <Footer />        {/* Footer copyright */}
    </div>
  )
}
▶ Try it Yourself

Dimension React Vue Angular
Developer Meta (Facebook) You Yuxi (Individual) Google
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
100%
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

JSX
// ============================================
// 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: LikeButton is an independent component that can be reused multiple times
  • State Management: liked and count are automatically tracked by React; no manual DOM manipulation is required

▶ Example 2: Visualization of the React component tree

Output:

TEXT
Displays: "' +        '". Button: Add to Cart
JSX
// ============================================
// 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:

TEXT
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

Q Is React a framework or a library?
A React is officially positioned as a "UI library," not a full-fledged framework. It handles only the "view layer"; features such as routing, state management, and HTTP requests require the use of community-developed libraries. This is also what makes React so flexible—you’re free to choose which tools to pair it with.
Q What do I need to learn before studying React?
A You need a basic understanding of JavaScript (ES6+: arrow functions, destructuring assignment, module imports and exports, Promises, and assíncrono/await). If you don’t know TypeScript yet, you can learn JavaScript first and then transition to TypeScript, or you can learn TypeScript directly (Lesson 23 of this tutorial will cover React + TypeScript in detail). A basic understanding of HTML and CSS is also necessary.
Q Should I choose React 18 or React 19?
A This tutorial is based on React 18.3 (the current LTS stable release). In Phase 5, we’ll cover the new features in React 19 (such as the use() hook, Server Components, and Actions). For production environments, we recommend starting with React 18 and upgrading once the React 19 ecosystem has matured.
Q Should I use Vite or Create React App (CRA) to create a React project?
A We recommend Vite. CRA is essentially no longer maintained (there have been no major updates since 2023), and Vite is far superior to CRA in both startup speed (<1 second vs. CRA’s 10–30 seconds) and build speed. Starting with Lesson 2, we’ll be using Vite throughout the course.
Q Is React outdated now? Should I just learn Next.js instead?
A Not at all. React is still the most popular front-end library, with over 230k ⭐ on GitHub and over 40 million weekly downloads on npm. Next.js is built on top of React, so if you don’t understand React’s core concepts (components, Hooks, state management), learning Next.js directly will be very challenging. I recommend learning the basics of React first, then moving on to Next.js (Phase 5 of this tutorial will cover this).

📖 Summary


📝 Exercises

  1. 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.
  2. 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).
  3. 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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏