What are Controlled Components in React?
This article provides a clear and concise explanation of controlled components in React. You will learn what controlled components are, how they work, how they differ from uncontrolled components, and how to implement them in your projects with practical code examples.
Understanding Controlled Components
In React, a controlled component is an input form element whose value is controlled by the React state. Instead of the browser’s Document Object Model (DOM) maintaining the state of the input, the React component itself keeps track of the input’s current value in its internal state.
In a traditional HTML form, form elements like
<input>, <textarea>, and
<select> typically maintain their own state and
update it based on user input. In React, a controlled component
overrides this default behavior, making the React state the “single
source of truth” for the input’s data.
How Controlled Components Work
To create a controlled component in React, you need to follow three main steps:
- Initialize State: Define a state variable using the
useStatehook to store the input’s value. - Bind the Value: Set the
valueattribute of the input element to your state variable. - Handle Changes: Create an
onChangeevent handler that updates the state variable whenever the user types or changes the input value.
Here is a basic code example demonstrating a controlled text input:
import React, { useState } from 'react';
function NameForm() {
const [name, setName] = useState('');
const handleChange = (event) => {
setName(event.target.value);
};
const handleSubmit = (event) => {
event.preventDefault();
alert('A name was submitted: ' + name);
};
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input type="text" value={name} onChange={handleChange} />
</label>
<button type="submit">Submit</button>
</form>
);
}
export default NameForm;In this example, every keystroke triggers the
handleChange function, which updates the React state. React
then re-renders the component, ensuring the input display is always in
sync with the state.
Why Use Controlled Components?
Controlled components offer several advantages over uncontrolled components, particularly when dealing with complex form interactions:
- Instant Field Validation: You can validate user input in real-time as they type (e.g., checking if an email is formatted correctly or if a password meets strength requirements).
- Conditional UI Elements: You can easily disable or enable form submission buttons based on whether the form state is valid.
- Enforcing Specific Formats: You can manipulate the user’s input before saving it to state (e.g., automatically converting lowercase letters to uppercase).
- Pre-filling Form Fields: Because the input value is bound to the state, you can easily populate form fields with data fetched from an API.
Controlled vs. Uncontrolled Components
While controlled components are the standard approach in React, you may sometimes encounter uncontrolled components.
- Controlled Components: React manages the form data. Every state mutation has an associated handler function. This approach is highly recommended for most form scenarios in React.
- Uncontrolled Components: The DOM handles the form
data. Instead of writing an event handler for every state update, you
use a
refto pull the values from the DOM when you need them. Uncontrolled components are simpler to set up for basic forms but offer less control over real-time validation and UI updates.