React Introduction | Tutorial
React is a JavaScript library developed by Facebook (now Meta) and open-sourced in 2013, specifically designed for building user interfaces, especially single-page applications (SPAs).
React allows developers to build reusable UI components using a declarative approach.
Reactβs Positioning
- Not a framework, but a library: React focuses solely on the view layer (the βVβ in MVC), unlike Angular, which provides a complete framework solution.
- Component-based thinking: Split the UI into independent, reusable components.
- JavaScript-centric: Everything is JavaScript, including structure, styling, and logic.
Core Features of React
1. Declarative Programming
Traditional imperative programming: Tell the computer how to do something.
// Native JavaScript (imperative)
const button = document.getElementById('myButton');
button.addEventListener('click', function() {
const counter = document.getElementById('counter');
const currentValue = parseInt(counter.textContent);
counter.textContent = currentValue + 1;
});
React declarative programming: Tell the computer what result you want.
// React (declarative)
function Counter() {
const [count, setCount] = useState(0);
return <button onClick={() => setCount(count + 1)}>{count}</button>;
}
Advantages:
- Code is more concise and intuitive
- Easier to understand and maintain
- Reduces errors from manual DOM manipulation
- Keeps state and UI in sync
2. Component-Based Architecture
The core idea of React is component-based thinking: decompose the UI into independent, reusable, and composable componentsβlike building with LEGO bricks. Each component only concerns itself with its own state (state) and properties (props), resulting in clear logic and easy maintenance.
A React application consists of individual components, each of which:
- Encapsulates its own structure, styling, and logic
- Can receive inputs (
props) - Can maintain internal state (
state) - Can be reused and composed
Example
// A simple component
function Welcome({ name }){
return <h1>Hello, {name}!</h1>;
}
// Reusing and composing components
function App(){
return(
<div>
<Welcome name="Alice"/>
<Welcome name="Bob"/>
<Welcome name="Charlie"/>
</div>
);
}
Advantages of componentization:
- Reusability: The same component can be used in multiple places
- Maintainability: Modifying a component does not affect other parts
- Testability: Independent components are easy to unit test
- Collaboration: Team members can develop different components in parallel
3. Virtual DOM
What is the Virtual DOM?
The Virtual DOM is a lightweight JavaScript object representation of the real DOMβa data structure stored in memory.
How it works:
- State change β
- Generate a new Virtual DOM tree β
- Compare with the old Virtual DOM tree (Diffing) β
- Calculate the minimal differences (Reconciliation) β
- Update only the changed parts in the real DOM
Diagram explanation:
- The Virtual DOM is a lightweight JavaScript object representation of the browserβs DOM.
- When state changes, the framework (e.g., React) first performs calculations and comparisons (diff algorithm) in the Virtual DOM.
- Then, via the patch process, only the minimal necessary updates are applied to the Real DOM.
Why do we need the Virtual DOM?
Problems with direct DOM manipulation:
- DOM operations are very slow (compared to JavaScript computation)
- Frequent DOM operations cause page reflows and repaints
- Direct DOM manipulation is error-prone
Advantages of the Virtual DOM:
- Performance optimization: Batch updates, reducing the number of real DOM operations
- Cross-platform support: The Virtual DOM can render to different platforms (Web, mobile, desktop)
- Declarative: Developers only need to concern themselves with state, not manual DOM manipulation
Example comparison:
// Assume we want to update 1000 list items
const items = Array(1000).fill(0).map((_, i) => i);
// Traditional approach: manipulate real DOM each time (slow)
items.forEach(item => {
const li = document.createElement('li');
li.textContent = item;
ul.appendChild(li); // 1000 DOM operations
});
// React approach: batch updates via Virtual DOM
function ItemList() {
return (
<ul>
{items.map(item => <li key={item}>{item}</li>)}
</ul>
);
}
// React intelligently batches DOM updates.
4. Unidirectional Data Flow
In React, data flows unidirectionally downward: Parent β Child. Children cannot directly update parent data:
React uses a top-down data flow pattern:
Parent component β (via props) β Child component β (via props) β Grandchild component
Characteristics:
- Data flows from parent to child components
- Child components communicate upward via callback functions
- Data flow is clear, making it easier to trace and debug
Example
function Parent(){
const [message, setMessage] = useState('Hello');
return(
<Child
message={message} // Data flows downward
onUpdate={setMessage} // Communicate upward via callback
/>
);
}
function Child({ message, onUpdate }){
return(
<div>
<p>{message}</p>
<button onClick={() => onUpdate('Updated!')}>
Update
</button>
</div>
);
}
Key Advantages of React
1. Relatively Gentle Learning Curve
- Small core API surface
- Primarily uses JavaScript knowledge
- Clear concepts and comprehensive documentation
2. Powerful Ecosystem
- Routing: React Router
- State management: Redux, Zustand, Jotai
- UI libraries: Material-UI, Ant Design, Chakra UI
- Toolchain: Create React App, Vite, Next.js
3. Extensive Community Support
- One of the most popular frontend libraries on GitHub
- Vast number of third-party components and tools
- Active community and abundant learning resources
4. Excellent Performance
- Virtual DOM optimization
- On-demand rendering
- Support for code splitting and lazy loading
5. Cross-Platform Capability
- React Native: Build mobile applications
- React Native for Windows: Build desktop applications
- React 360: Build VR applications
6. Enterprise-Grade Application Support
Used by numerous well-known companies:
- Facebook/Meta
- Netflix
- Airbnb
- Uber
- Tencent, Alibaba, etc.
Appropriate Use Cases for React
Scenarios well-suited for React:
- Single-page applications (SPAs)
- Dynamic interfaces requiring frequent updates
- Complex, interactive UIs
- Large projects requiring component reuse
- Applications needing cross-platform development
Scenarios less suitable for React:
- Simple static websites (may be overkill)
- Websites with extremely high SEO requirements (requires SSR solutions like Next.js)
- Teams unfamiliar with JavaScript
Comparison with Other Frameworks
| Feature | React | Vue | Angular |
|---|---|---|---|
| Type | Library | Progressive Framework | Full-featured Framework |
| Learning Curve | Moderate | Relatively gentle | Relatively steep |
| Flexibility | High | Moderate | Low (many conventions) |
| Ecosystem | Very rich | Rich | Well-integrated |
| Enterprise Support | Meta | Independent | |
| TypeScript Support | Good | Good | Natively supported |
History of React
- 2013: React open-sourced
- 2015: React Native released
- 2016: React 16 (Fiber architecture)
- 2019: React Hooks officially released
- 2020: Concurrent Mode (experimental)
- 2022: React 18 (Concurrent Rendering)
- 2024β2025: New features such as React Compiler and Server Components
YouTip