Controlled vs Uncontrolled Components in React: State Management

🚀 Controlled vs Uncontrolled Components in React When handling forms in React, we often use either Controlled or Uncontrolled components. The difference is about who manages the input data. 🔵 Controlled Component A controlled component is an input field whose value is managed by React state. 👉React becomes the single source of truth. Example: import { useState } from "react"; function ControlledForm() { const [name, setName] = useState(""); return ( <input type="text" value={name} onChange={(e) => setName(e.target.value)} /> ); } Here ●'useState' stores the input value. ●Every time the user types, 'onChange' updates the state. ●The input always displays the value from React state. ✅ Best for validation, dynamic UI updates, and complex forms. 🟠 Uncontrolled Component An uncontrolled component stores its data in the DOM, not in React state. 👉 React accesses the value only when needed using 'useRef'. Example: import { useRef } from "react"; function UncontrolledForm() { const nameRef = useRef(); const handleSubmit = () => { alert(nameRef.current.value); }; return ( <> <input type="text" ref={nameRef} /> <button onClick={handleSubmit}>Submit</button> </> ); } Here ●The input manages its own value internally. ●'useRef' is used to access the value when the button is clicked. ●React does not track every keystroke. ✅ Best for simple forms or quick implementations. 💡 Difference: ■Controlled → React controls the data. ■Uncontrolled → DOM controls the data. Understanding this concept helps in building cleaner, more predictable, and scalable React applications. #ReactJS #FrontendDevelopment #JavaScript #WebDevelopment #ReactLearning

  • 

🚀 Controlled vs Uncontrolled Components in React

To view or add a comment, sign in

Explore content categories