What are Uncontrolled Components in React?
In React, Uncontrolled Components are form inputs (like <input>
, <textarea>
, and <select>
) that manage their own state internally, rather than relying on React's state management. Instead of controlling the input’s value via React’s state
, you access the input’s current value directly from the DOM using a ref.
In simple words, with uncontrolled components:
- The form data is handled by the DOM itself.
- React does not "control" the input value during the user’s interaction.
- You typically use a
ref
to read values when needed (e.g., on form submission).
Example of an Uncontrolled Component:
import React, { useRef } from "react"; function UncontrolledForm() { const inputRef = useRef(null); const handleSubmit = (e) => { e.preventDefault(); alert(`Input Value: ${inputRef.current.value}`); }; return ( <form onSubmit={handleSubmit}> <input type="text" ref={inputRef} /> <button type="submit">Submit</button> </form> ); } export default UncontrolledForm;
Key Points:
- You don't need to update state on every keystroke.
- Useful for quick forms, integrations with non-React libraries, or when you want less React overhead.
- Less powerful for complex form validation compared to controlled components.