Loading...
Loading...
By continuing to use the platform, you accept the terms of the Privacy Policy and the use of cookies.
👋 Hi! I'm Dastan, author of Hack Frontend. Always open to professional networking => connect with me on LinkedIn.
In React when working with forms there are two approaches to managing field values: controlled and uncontrolled components.
This is a component where form value is stored in React component state, and any user input change happens through onChange and state update.
import { useState } from "react";
function ControlledInput() {
const [value, setValue] = useState("");
return (
<input
type="text"
value={value}
onChange={(e) => setValue(e.target.value)}
/>
);
}
Here:
value is managed through React stateThis is a component where value isn't stored in React state but is extracted directly from DOM using ref.
import { useRef } from "react";
function UncontrolledInput() {
const inputRef = useRef();
const handleSubmit = () => {
alert(inputRef.current.value);
};
return (
<>
<input type="text" ref={inputRef} />
<button onClick={handleSubmit}>Submit</button>
</>
);
}
Here:
input has right now| Controlled component | Uncontrolled component | |
|---|---|---|
| Where value stored | In React state | In DOM via ref |
| React "knows" value? | Yes | No |
| Suitable for validation | Excellent fit | Harder to implement |
| Performance | May re-render more often | Faster for large forms |
| Implementation simplicity | Slightly more complex | Simpler in simple scenarios |
Controlled:
Uncontrolled:
Tip:
Use controlled components when you need to control state and do validation. For simple forms or integration with formData uncontrolled are better fit.