- Published on
Controlled Component vs Uncontrolled Components
4 min read
- Authors
- Name
- Shuwen
Table of Contents
Controlled Component vs Uncontrolled Components
When building forms in React, you can manage inputs in two main ways: controlled components and uncontrolled components. The difference comes down to where the source of truth for the input value lives.
Controlled Component
Imagine you're building a registration form and you want real-time validation while users type. In a controlled component, React state drives the input value, so you can validate on every change.
import React, { useState } from 'react';
function RegistrationForm() {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const handleUsernameChange = (event) => {
setUsername(event.target.value);
};
const handlePasswordChange = (event) => {
setPassword(event.target.value);
};
const handleSubmit = (event) => {
alert('A form was submitted: ' + username + ' ' + password);
event.preventDefault();
};
return (
<form onSubmit={handleSubmit}>
<label>
Username:
<input type="text" value={username} onChange={handleUsernameChange} />
</label>
<label>
Password:
<input type="password" value={password} onChange={handlePasswordChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
export default RegistrationForm;
Uncontrolled Component
Suppose you're building a simple search bar and don't need live validation. An uncontrolled component lets the DOM manage the input value, and you read it only on submit.
import React, { useRef } from 'react';
function SearchBar() {
const input = useRef();
const handleSubmit = (event) => {
alert('Search term: ' + input.current.value);
event.preventDefault();
};
return (
<form onSubmit={handleSubmit}>
<input type="text" ref={input} placeholder="Search..." />
<input type="submit" value="Search" />
</form>
);
}
export default SearchBar;
Both approaches are valid. Controlled components are great when you need immediate feedback or complex validation, while uncontrolled components keep things simple for lightweight forms.
