Unidirectional Data Flow (Luồng dữ liệu một chiều) trong React có nghĩa là:
- Dữ liệu luôn chảy theo một hướng duy nhất: Từ Component cha xuống Component con (thông qua
props). - Component con không bao giờ được phép thay đổi trực tiếp
propsmà nó nhận được.
Cách con cập nhật dữ liệu của cha:
Con muốn cập nhật dữ liệu thì phải gọi một callback function (hàm) do cha truyền xuống.
Ví dụ:
function Parent() {
const [text, setText] = useState("");
return <Child value={text} onUpdate={setText} />;
}
function Child({ value, onUpdate }) {
// Con gọi onUpdate để yêu cầu cha thay đổi state
return <input value={value} onChange={e => onUpdate(e.target.value)} />;
}Lợi ích:
- Dễ dự đoán & Dễ gỡ lỗi (Debug): Nhờ việc chỉ có một "nguồn sự thật" (Single Source of Truth) và luồng chảy rõ ràng, bạn dễ dàng trace (lần dấu) xem lỗi data xuất phát từ đâu.
- Khác với cơ chế Two-way data binding (Binding 2 chiều) của Angular 1 (nơi UI thay đổi data và data thay đổi UI tự động), luồng một chiều giúp tránh được các vòng lặp cập nhật vô tận (circular dependencies).
Unidirectional Data Flow in React means:
- Data always flows in a single direction: From Parent component down to Child component (via
props). - A child component is never allowed to mutate the
propsit receives directly.
How a child updates parent data:
If a child needs to update the data, it must call a callback function passed down by the parent.
Example: <Input onChange={handleChange} /> - the Input component calls onChange, but the actual logic that changes the state lives inside the parent's handleChange function.
Benefits:
- Predictable & Easy to Debug: Having a "Single Source of Truth" and a clear flow makes it much easier to trace where data bugs originate.
- Unlike the Two-way data binding of Angular 1 (where UI updates data and data updates UI automatically), the unidirectional flow prevents infinite update loops (circular dependencies).