Chuyển đến nội dung chính

Bài 1: Giới thiệu React

React là gì, Virtual DOM, component-based architecture. So sánh React vs Vue vs Angular vs Svelte. Tooling ecosystem, create-react-app vs Vite. JSX syntax, first component.

💻 Lập trình — Bài 1 Bài 1: Giới thiệu React

React & Next.js: Từ Cơ bản đến Nâng cao

Phần 1: React Fundamentals

xdev.asia

1. React là gì?

React là thư viện JavaScript để xây dựng giao diện người dùng (UI), được phát triển bởi Meta (Facebook). React không phải là framework — nó chỉ tập trung vào view layer và cho phép bạn tự chọn các tools khác cho routing, state management, data fetching.

1.1. Core Concepts

  • Component-Based: UI được chia thành các components độc lập, tái sử dụng
  • Declarative: Mô tả UI nên trông như thế nào, React tự handle DOM updates
  • Virtual DOM: React tạo DOM ảo trong memory, so sánh và chỉ update phần thay đổi
  • Unidirectional data flow: Data chảy từ parent → child qua props

1.2. Virtual DOM hoạt động như thế nào?

User Action → setState() → Virtual DOM re-render (in memory)
    → Diffing (so sánh Virtual DOM cũ và mới)
    → Reconciliation (chỉ update DOM thật ở phần thay đổi)

2. So sánh React vs Vue vs Angular vs Svelte

FeatureReactVueAngularSvelte
TypeLibraryFrameworkFrameworkCompiler
Learning CurveMediumEasyHardEasy
Bundle Size~45KB~33KB~143KB~2KB
PerformanceFast (Virtual DOM)Fast (Virtual DOM)Fast (Change Detection)Fastest (No runtime)
EcosystemLargestLargeCompleteGrowing
TypeScriptExcellentGoodBuilt-inGood
SSRNext.jsNuxtAngular UniversalSvelteKit
JobsMostManyManyGrowing

3. Setup Project với Vite

# Create React + TypeScript project
npm create vite@latest my-app -- --template react-ts

cd my-app
npm install
npm run dev

3.1. Project Structure

my-app/
├── public/
│   └── vite.svg
├── src/
│   ├── assets/
│   ├── App.tsx          ← Root component
│   ├── App.css
│   ├── main.tsx         ← Entry point
│   └── vite-env.d.ts
├── index.html
├── package.json
├── tsconfig.json
└── vite.config.ts

4. JSX Syntax

// JSX = JavaScript XML
// Cho phép viết HTML-like syntax trong JavaScript

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

// ↓ Biên dịch thành
const element = React.createElement('h1', null, 'Hello, React!');

4.1. JSX Rules

function App() {
  const name = 'Duy';
  const isLoggedIn = true;
  const items = ['React', 'Vue', 'Angular'];

  return (
    // Rule 1: Phải có 1 root element (hoặc Fragment)
    <>
      {/* Rule 2: Expressions trong {} */}
      <h1>Hello, {name}!</h1>

      {/* Rule 3: className thay vì class */}
      <div className="container">
        {/* Rule 4: htmlFor thay vì for */}
        <label htmlFor="email">Email</label>

        {/* Rule 5: CamelCase cho attributes */}
        <input onClick={() => {}} tabIndex={0} />

        {/* Rule 6: Self-closing tags */}
        <img src="logo.png" alt="Logo" />
        <br />

        {/* Conditional rendering */}
        {isLoggedIn && <p>Welcome back!</p>}
        {isLoggedIn ? <Dashboard /> : <Login />}

        {/* List rendering */}
        <ul>
          {items.map((item, index) => (
            <li key={index}>{item}</li>
          ))}
        </ul>

        {/* Inline styles (object, camelCase) */}
        <div style={{ backgroundColor: 'blue', fontSize: '16px' }}>
          Styled div
        </div>
      </div>
    </>
  );
}

5. First Component

// src/components/Greeting.tsx
function Greeting() {
  return (
    <div>
      <h1>Xin chào từ React! 🚀</h1>
      <p>Đây là component đầu tiên của bạn.</p>
    </div>
  );
}

export default Greeting;

// src/App.tsx
import Greeting from './components/Greeting';

function App() {
  return (
    <div>
      <Greeting />
    </div>
  );
}

export default App;

Bài tiếp theo: Components, Props & TypeScript — functional components, typing props, và component composition.