Controlled Component (Component được kiểm soát) là component mà giá trị của các form element (như <input>, <textarea>, <select>) được kiểm soát hoàn toàn bởi React state.
- Thay vì để DOM tự quản lý trạng thái, React state sẽ là "source of truth" (nguồn chân lý duy nhất).
- Mỗi khi người dùng gõ phím, một sự kiện
onChangesẽ được gọi để cập nhật state, và propvaluecủa input sẽ phản ánh state đó.
// Ví dụ Controlled Component:
function ControlledInput() {
const [text, setText] = useState("");
return <input value={text} onChange={(e) => setText(e.target.value)} />;
}Khác biệt với Uncontrolled Component:
- Uncontrolled Component lưu trữ trạng thái trực tiếp trong DOM thật. Bạn dùng ref để trích xuất giá trị từ DOM khi cần (vd: khi submit form).
- Khi nào dùng: Controlled Component được khuyến nghị trong hầu hết trường hợp vì nó cho phép bạn validate dữ liệu realtime, vô hiệu hóa nút submit, và định dạng input dễ dàng. Uncontrolled Component thường dùng khi tích hợp với thư viện non-React hoặc khi cần xử lý form cực kỳ lớn mà không muốn re-render liên tục.
A Controlled Component is one where the value of form elements (like <input>, <textarea>, <select>) is completely controlled by React state.
- Instead of the DOM managing its own state internally, React state becomes the "single source of truth".
- Every time the user types, an
onChangeevent fires to update the state, and the input'svalueprop reflects that state.
// Controlled Component Example:
function ControlledInput() {
const [text, setText] = useState("");
return <input value={text} onChange={(e) => setText(e.target.value)} />;
}Difference from Uncontrolled Component:
- Uncontrolled Components store their state directly in the actual DOM. You use a ref to pull values from the DOM when needed (e.g., on form submit).
- When to use: Controlled components are recommended for most cases because they allow real-time validation, dynamic button disabling, and input formatting. Uncontrolled components are useful when integrating with non-React libraries or handling massive forms where you want to avoid frequent re-renders.