Uncontrolled Components
Uncontrolled Components & Refs
◆ Definition
Uncontrolled Component: An input element that stores its own value in the DOM, not in React state. React accesses the current value only when needed (e.g., on submit), using a ref to reach into the DOM node directly.
Uncontrolled inputs behave like traditional HTML forms, they’re simpler to set up but offer less real-time control. Most useful for file inputs, integrating with third-party DOM libraries, or performance-critical forms with hundreds of fields.
JSX — UncontrolledForm.jsx
import { useRef } from 'react'; function UncontrolledForm() { const usernameRef = useRef(null); // ref points to DOM node const emailRef = useRef(null); const handleSubmit = (e) => { e.preventDefault(); // Read DOM values only at submission time console.log({ username: usernameRef.current.value, email: emailRef.current.value, }); // Manually reset the DOM fields usernameRef.current.value = ''; emailRef.current.value = ''; }; return ( <form onSubmit={handleSubmit}> {/* defaultValue sets initial value; React does NOT track changes */} <input ref={usernameRef} defaultValue="" type="text" placeholder="Username" /> <input ref={emailRef} defaultValue="" type="email" placeholder="Email" /> <button type="submit">Submit</button> </form> ); } export default UncontrolledForm;
Always use
defaultValue(notvalue) for uncontrolled inputs. SettingvaluewithoutonChangecreates a read-only input and React will throw a console warning.
