React Controlled vs Uncontrolled Components
In React, controlled and uncontrolled components are two different approaches to managing form inputs and handling user input.
1) Controlled Components
A controlled component is one where React has full control over the form input state. The component renders an input element and manages its value and changes through state.
The state is typically stored in the component’s state or received as props from a parent component. When the input value changes, the component’s state is updated, causing a re-render and reflecting the updated value in the input field.
Controlled components provide a straightforward way to manage the input state, validate and manipulate the input value, and react to changes.
Example of Controlled Component
import React, { useState } from 'react';
function ControlledComponent() {
const [inputValue, setInputValue] = useState('');
const handleChange = (event) => {
setInputValue(event.target.value);
};
return (
<input
type="text"
value={inputValue}
onChange={handleChange}
/>
);
}
In the example above, the input field is controlled by the inputValue
state variable. Whenever the user types into the input field, the handleChange
function updates the state value, causing a re-render and updating the input's value accordingly.
2) Uncontrolled Component
Uncontrolled components, on the other hand, leave the form input state management to the DOM. Instead of controlling the input’s value through React state, you let the DOM handle it directly using the ref
attribute. You can access the input value using JavaScript DOM methods or by querying the DOM.
Uncontrolled components can be useful in cases where you don’t need to perform fine-grained control over the input state or need to integrate with legacy code or third-party libraries.
Example of Uncontrolled Component
import React, { useRef } from 'react';
function UncontrolledComponent() {
const inputRef = useRef();
const handleButtonClick = () => {
const inputValue = inputRef.current.value;
// Do something with the input value
};
return (
<div>
<input type="text" ref={inputRef} />
<button onClick={handleButtonClick}>Submit</button>
</div>
);
}
In the above example, the inputRef
is used to access the input's value when the button is clicked. React doesn't have control over the input state, and you need to manually retrieve the value from the DOM.
Key take aways
Both controlled and uncontrolled components have their use cases, and the choice depends on the specific requirements of your application. Controlled components offer more control and allow for easier validation and manipulation, while uncontrolled components can be simpler in certain scenarios but offer less direct control over the input state.