React Controlled vs Uncontrolled Components Explained

⚛️ Top 150 React Interview Questions – 33/150 📌 Topic: Controlled vs Uncontrolled Components 🔹 WHAT is it? This topic describes how form data (input values) is handled in React. Controlled Component: The input value is driven by React State. React is the boss of the data. Uncontrolled Component: The input value is handled by the DOM itself. You read the value only when needed using a ref. 🔹 WHY is it designed this way? React provides these two patterns to balance control and simplicity. Controlled (Standard): Needed for instant validation, showing errors while typing, or disabling buttons until the form is valid. Uncontrolled (Edge Case): Useful when integrating with non-React libraries or when you only care about the value at form submission. 🔹 HOW do you do it? (Implementation) Controlled Component (using State): function ControlledForm() { const [name, setName] = useState(""); return ( <input value={name} onChange={(e) => setName(e.target.value)} /> ); } Uncontrolled Component (using Ref): function UncontrolledForm() { const inputRef = useRef(null); const handleSubmit = () => { alert("Name: " + inputRef.current.value); }; return ( <> <input ref={inputRef} type="text" /> <button onClick={handleSubmit}>Submit</button> </> ); } 🔹 WHERE are the best practices? Default to Controlled: Use Controlled Components in most cases. They are more predictable and easier to manage. Use for Validation: Real-time features like character count or password strength checks require Controlled components. defaultValue: In Uncontrolled components, use defaultValue instead of value so the DOM manages updates. 📝 Summary for your notes: A Controlled component is like a Puppet 🪀 — it moves only when React (State) pulls the strings. An Uncontrolled component is like a Wild Animal 🐾 — it does its own thing, and you check on it using a Ref. 👇 Comment “React” if this series is helping you 🔁 Share with someone preparing for React interviews #ReactJS #FrontendDevelopment #ReactInterview #JavaScript #WebDevelopment #LearningInPublic #Top150ReactQuestions

  • text, letter

To view or add a comment, sign in

Explore content categories