An explanation of controlled vs uncontrolled components.
Join DevzConnect — where devs connect, code, and level up together. Got questions? Stuck on a bug? Or just wanna help others crush it? Jump in and be part of a community that gets it
Welcome back to DevzConnect — where devs connect, code, and level up together. Ready to pick up where you left off? Dive back in, ask questions, share wins, or help others crush their goals!
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In React, controlled and uncontrolled components refer to how the form elements (like input fields, textareas, etc.) manage their state.
1️⃣ Controlled Components 🎮
What it is:
A controlled component is one where the form element’s value is controlled by React’s state. The state is the “single source of truth,” meaning React is fully responsible for managing the value of the input field.
How it works:
The input value is tied to a piece of state, and any change in the input updates that state via an
onChangehandler.Example:
Key Points:
2️⃣ Uncontrolled Components 🕹️
What it is:
An uncontrolled component manages its own state internally (the browser handles it). In this case, React doesn’t directly manage the form element’s value. Instead, it relies on a ref to access the current value.
How it works:
The value of the input is handled by the DOM itself. React only interacts with the component when necessary (e.g., reading its value using a
ref).Example:
Key Points:
refsto access the input value when needed.3️⃣ Comparison 📊
ref)refordefaultValueonChange)value={value} onChange={handleChange}ref={inputRef}4️⃣ When to Use Which? 🤔
Use Controlled Components when:
Use Uncontrolled Components when:
Summary 💡