Mastering Form Handling in React: Controlled vs Uncontrolled Components
Forms are a fundamental building block of web development, and with the rise of React, handling form data has become more nuanced. In this article, we’ll explore the two approaches to managing form data in React components: controlled and uncontrolled components.
What are Controlled Components?
Controlled components are those where form data is handled by the component’s state. This means that the state becomes the single source of truth for the input elements. When a user interacts with a form element, the component’s state is updated, and the input element’s value is reflected accordingly.
How Do Controlled Components Work?
Let’s take a look at an example:
“`
const App = () => {
const [name, setName] = useState(”);
const [email, setEmail] = useState(”);
return (
);
};
“
useState
In this example, we're using thehook to create two states:
nameand
email. These states are then assigned to the
valueproperty of the corresponding input elements. When the user types something into the input fields, the
onChange` event is triggered, updating the state accordingly.
What are Uncontrolled Components?
Uncontrolled components, on the other hand, rely on the DOM to handle form data. This means that the values of the form elements are stored directly on the DOM, and we need to access them using DOM APIs.
How Do Uncontrolled Components Work?
Let’s refactor the previous example to use uncontrolled components:
“`
const App = () => {
const nameRef = React.createRef();
const emailRef = React.createRef();
return (
);
};
“
nameRef
In this example, we're creating two React refs,and
emailRef, and assigning them to the
refattribute of the corresponding input elements. We can then access the values of the input elements using the
current` property of the refs.
Controlled vs Uncontrolled Components: Key Differences
So, what are the key differences between controlled and uncontrolled components?
- Predictability: Controlled components are predictable because the state of the form elements is handled by the component. Uncontrolled components, on the other hand, can be affected by external factors.
- Form Validation: Controlled components enable effective form validation, as the values are stored in the component’s state. Uncontrolled components require more effort to validate.
- Control: Controlled components give you more control over the form elements’ values, allowing you to dictate what can and cannot be inserted.
Which One Should You Use?
The choice between controlled and uncontrolled components ultimately depends on your use case and personal preference. Controlled components offer more control and predictability, while uncontrolled components provide a more traditional approach to form handling.
Get Started with LogRocket
Want to take your React error tracking to the next level? Sign up for LogRocket and start monitoring your app’s performance in minutes.