Controlled vs Uncontrolled ComponentsIntermediate
1Question 1 of 1
javascriptWhat is the difference between Controlled and Uncontrolled Components in React?
Explanation & Concept
• Controlled Components: Form input state is driven entirely by React state (`value` and `onChange`). React acts as the single source of truth. • Uncontrolled Components: Form input data is handled by the browser DOM itself. Values are retrieved on demand using a `ref` (`useRef`).
Code Example
javascript
import { useState, useRef } from "react";
export function FormComparison() {
// 1. Controlled Input
const [controlledEmail, setControlledEmail] = useState("");
// 2. Uncontrolled Input using Ref
const passwordRef = useRef();
const handleSubmit = (e) => {
e.preventDefault();
console.log("Email:", controlledEmail);
console.log("Password:", passwordRef.current.value);
};
return (
<form onSubmit={handleSubmit}>
<input value={controlledEmail} onChange={(e) => setControlledEmail(e.target.value)} />
<input ref={passwordRef} type="password" defaultValue="" />
<button type="submit">Submit</button>
</form>
);
}How It Works & Key Takeaways
Controlled inputs allow real-time validation, masking, and conditional disabling, while uncontrolled inputs can reduce re-renders for large complex forms.
Mock Test · 1 Questions · Optional
Ready for React Keys & Lists?
Take a quick test to evaluate yourself, or move straight to the next module.
Intermediate1 questions