Skip to content

Pattern trong React

Reconciler của React là một lớp học mẫu mực về cách kết hợp các pattern cấp thấp. Năm pattern đầu tiên xuất hiện trong cùng một chu trình render.

Pattern trong chu trình render

PatternỞ đâu trong ReactTác dụng
BitmaskReactFiberFlags.jsFlag tác động phụ trên node fiber
Double BufferingFiber current / alternateHoán đổi cây nguyên tử khi reconciliation
Cooperative SchedulingworkLoopConcurrentYield mỗi 5ms để giữ UI phản hồi
Min HeapSchedulerMinHeap.jsHàng đợi ưu tiên cho task đã lập lịch
Diff / PatchReactChildFiber.jsReconcile danh sách con cũ và mới

Cách chúng kết hợp: Một chu trình render

Khi bạn gọi setState, cả năm pattern bắn theo thứ tự:

setState()
1
Min Heap

Scheduler inserts an update task with priority (lanes). The heap ensures the highest-priority update runs first.

2
Cooperative Scheduling

workLoopConcurrent processes one fiber at a time, checking shouldYield() every 5ms. If the browser needs the thread, React pauses and resumes later.

3
Diff / Patch

For each fiber, reconcileChild compares old children vs new children. It finds the minimal set of DOM operations.

4
Bitmask

Each diffed fiber gets side-effect flags set: Placement|Update|Deletion. Flags are OR'd together and bubble up the tree.

5
Double Buffering

The entire render builds on the workInProgress tree. On commit, React swaps current ↔ workInProgress atomically. The old tree becomes the next workInProgress.

Insight then chốt: các pattern này không phải tính năng độc lập — chúng tạo thành một pipeline. Heap quyết định cái gì để render, cooperative scheduling quyết định khi nào render, diff/patch quyết định cái gì đã đổi, bitmask mã hoá nó đổi như thế nào và double buffering đảm bảo hoán đổi là nguyên tử.

Xem Liên kết giữa các pattern để có sơ đồ kết hợp tương tác đầy đủ.

Thêm pattern trong React

PatternỞ đâu trong ReactTác dụng
Batch Processingunstable_batchedUpdatesNhiều cuộc gọi setState được gom vào một lần re-render
Dirty FlagReactFiberFlags.jsFlag fiber (Placement, Update, Deletion) đánh dấu subtree cần xử lý
ObserverMẫu cleanup useEffectĐăng ký khi mount, huỷ đăng ký khi cleanup — quan sát state tách rời

Đọc thêm

Released under the MIT License.