Photo by Ilya Pavlov on Unsplash
Difference between controlled and uncontrolled components in React.js
When working with forms in React.js, developers often encounter the terms "controlled components" and "uncontrolled components." These concepts represent two distinct approaches to managing form elements and their states within a React application. In this blog post, we'll delve into the differences between controlled and uncontrolled components, providing insights into when and why you might choose one over the other.
Controlled Components:
Controlled components in React.js are those in which the state of form elements, such as input fields, checkboxes, and radio buttons, is managed and controlled by React. This is achieved by binding the value of the form elements to the state and updating that state through event handlers, typically the onChange
event.
Let's take a look at an example of a controlled component:
import React, { useState } from 'react';
const ControlledComponent = () => {
const [inputValue, setInputValue] = useState('');
const handleChange = (event) => {
setInputValue(event.target.value);
};
return (
<input
type="text"
value={inputValue}
onChange={handleChange}
/>
);
};
In this example, the inputValue
state reflects the current value of the input field, and any changes to the input are managed through the handleChange
event handler.
Uncontrolled Components:
On the other hand, uncontrolled components allow form elements to maintain their own state within the DOM, without direct interference from React. The state is managed by the DOM itself, and you can access the values using refs.
Consider the following example of an uncontrolled component:
import React, { useRef } from 'react';
const UncontrolledComponent = () => {
const inputRef = useRef();
const handleClick = () => {
alert(`Input Value: ${inputRef.current.value}`);
};
return (
<>
<input type="text" ref={inputRef} />
<button onClick={handleClick}>Get Input Value</button>
</>
);
};
In this case, the inputRef
is used to access the current value of the input field directly from the DOM.
Choosing Between Controlled and Uncontrolled Components:
The decision to use controlled or uncontrolled components depends on the specific requirements of your application.
Controlled Components: Use them when you need centralized control over the form elements' state, such as when implementing validation or manipulating input before updating the state.
Uncontrolled Components: Opt for uncontrolled components when integrating React with non-React code or when you prefer to let the DOM handle the form element state.
Conclusion:
Understanding the distinction between controlled and uncontrolled components in React empowers developers to make informed decisions when building forms. Whether you need fine-grained control over state or prefer a more hands-off approach, React provides the flexibility to choose the best strategy for your application's needs.