Controlled vs Uncontrolled Components
Controlled vs Uncontrolled Components in React
In React, form inputs (like <input>, <textarea>, <select>, etc.) can be handled in two ways:
Controlled Components
Uncontrolled Components
These differ in how the form data is managed.
✅ Controlled Components
Definition:
A controlled component is an input element whose value is controlled by React state.
Key Features:
The form data is handled by the React component.
You use useState or similar hooks to store and update the value.
Provides better control and validation.
Example:
jsx
Copy
Edit
import React, { useState } from 'react';
function ControlledForm() {
const [name, setName] = useState('');
const handleChange = (event) => {
setName(event.target.value);
};
return (
<form>
<input type="text" value={name} onChange={handleChange} />
<p>You typed: {name}</p>
</form>
);
}
Benefits:
Easier to validate input.
Input state is always in sync with your component.
Good for dynamic and interactive forms.
❎ Uncontrolled Components
Definition:
An uncontrolled component stores its own state internally and is accessed using a ref.
Key Features:
The form data is handled by the DOM, not React.
You use React.createRef() or useRef() to access input values.
Simpler for quick forms or non-interactive inputs.
Example:
jsx
Copy
Edit
import React, { useRef } from 'react';
function UncontrolledForm() {
const inputRef = useRef();
const handleSubmit = (event) => {
event.preventDefault();
alert(`You typed: ${inputRef.current.value}`);
};
return (
<form onSubmit={handleSubmit}>
<input type="text" ref={inputRef} />
<button type="submit">Submit</button>
</form>
);
}
Benefits:
Less code and simpler setup.
Useful for integrating with non-React libraries.
🔍 Key Differences
Feature Controlled Component Uncontrolled Component
Data Source React state DOM (via refs)
Updates on Input Change Yes (onChange + useState) No direct updates in React state
React Control Full control Minimal control
Validation Easier Harder
Code Complexity More boilerplate Simpler
🧠 When to Use What?
Use Controlled Components when:
- You need to validate input on change
- You want to enable/disable fields dynamically
- You need to control the form flow
Use Uncontrolled Components when:
- You need simple input handling
- You’re integrating with legacy code or libraries
- Performance optimization for large forms
🧩 Conclusion
Controlled components give you more power and flexibility at the cost of more boilerplate.
Uncontrolled components are simpler and closer to traditional HTML forms but offer less control.
Understanding both helps you make the right decision based on the complexity and needs of your React application.
Learn React JS Course in Hyderabad
Read More
Building a Theme Toggler with useContext
Visit Our Quality Thought Training in Hyderabad
Comments
Post a Comment