Controlled vs Uncontrolled Components in React: A Beginner's Guide
Welcome back! In our previous lesson, we learned how to handle form input in React. Now, we're going to explore two important concepts: Controlled Components and Uncontrolled Components. Don't worry if you're not familiar with these terms yet – we'll break everything down step by step.
1. What Are Controlled Components?
In React, a Controlled Component is a component that controls its form elements using React's state. This means that React is in charge of managing the value of the input field. Let's look at a simple example to understand this better.
import React, { useState } from 'react';
function ControlledForm() {
const [value, setValue] = useState('');
const handleChange = (event) => {
setValue(event.target.value);
};
const handleSubmit = (event) => {
event.preventDefault();
console.log('Submitted value:', value);
};
return (
<form onSubmit={handleSubmit}>
<label htmlFor="controlled-input">Controlled Input:</label>
<input
type="text"
id="controlled-input"
value={value}
onChange={handleChange}
/>
<button type="submit">Submit</button>
</form>
);
}
export default ControlledForm;
Here's what's happening in the ControlledForm component:
- We use
useStateto create a state variable calledvalueand a functionsetValueto update it. - The
valueprop of the<input>is set to thevaluestate variable. This means that the input field always displays the current value of the state. - The
onChangeprop of the<input>is set tohandleChange, which updates the state whenever the user types in the input field. - When the form is submitted,
handleSubmitlogs the current value of the input to the console.
In a Controlled Component, React is responsible for the input's value. This allows us to easily access and manipulate the input value, perform validation, and control the input's behavior.
2. What Are Uncontrolled Components?
Uncontrolled Components are the opposite. Instead of using React's state to manage the form values, Uncontrolled Components rely on the DOM itself to handle form inputs. This means you use a ref to access the input's value when you need it.
import React, { useRef } from 'react';
function UncontrolledForm() {
const inputRef = useRef(null);
const handleSubmit = (event) => {
event.preventDefault();
console.log('Submitted value:', inputRef.current.value);
};
return (
<form onSubmit={handleSubmit}>
<label htmlFor="uncontrolled-input">Uncontrolled Input:</label>
<input
type="text"
id="uncontrolled-input"
ref={inputRef}
/>
<button type="submit">Submit</button>
</form>
);
}
export default UncontrolledForm;
Here's what's happening in the UncontrolledForm component:
- We use
useRefto create a reference calledinputRefthat will point to the input element. - The
refprop of the<input>is set toinputRef, which allows us to access the input element directly. - When the form is submitted,
handleSubmitlogs the current value of the input by accessinginputRef.current.value.
In an Uncontrolled Component, React does not control the input's value. Instead, we rely on the DOM to handle the form's state. This approach can be simpler for certain cases, but it offers less control over the input's behavior and value.
3. Key Differences Between Controlled and Uncontrolled Components
Let's summarize the main differences between Controlled and Uncontrolled Components:
- Control: In Controlled Components, React controls the input value through state. In Uncontrolled Components, the DOM handles the input value.
- Access: In Controlled Components, you access the input value through React's state. In Uncontrolled Components, you use a ref to access the input value directly from the DOM.
- Usage: Controlled Components are generally preferred for most use cases because they provide more control and allow for easier validation and manipulation of input values. Uncontrolled Components can be useful when you want to avoid the overhead of managing state or when working with third-party libraries that require direct DOM access.
4. Conclusion
We've explored Controlled and Uncontrolled Components in React. Controlled Components give you more control over form inputs by managing their state in React, while Uncontrolled Components rely on the DOM to manage the form inputs.
Both approaches have their use cases, and it's essential to choose the right one based on your needs. Experiment with both methods and see which one works best for your specific scenario. In our next lesson, we'll dive into handling multiple form fields and form validation.