Introduction
React is one of the most useful technologies for building dynamic and interactive web applications. These components are used for handling the form user inputs like text box, dropdown, checkbox, and Radio button, etc. Controlled components help manage the React state to handle the form data, and uncontrolled components are used to manage the DOM element to handle the form inputs.
In this article, we will discuss the difference between the controlled and uncontrolled components in React, exploring how to manage the form data, as well as advantages and disadvantages.
Controlled Component
With the use of this component, you are directly managing form user inputs such as text input, text area, etc., in the React state. If you want to directly update the form elements, you can easily do so through the React state. All changes in form elements are controlled by the event handlers such as useState and useEffect, etc. This component handles value props using the callbacks.
Syntax:
import React, { useState } from "react";
function Controlled() {
const [text, setText] = useState("");
return (
<div>
<input
value={text}
onChange={(e) => setText(e.target.value)}
/>
<p>{text}</p>
</div>
);
}
export default Controlled;
Example
Code:
import React, { useState } from "react";
function Age() {
const [age, setAge] = useState("");
return (
<div>
<h2>Using the Controlled Component</h2>
<h2>Enter Your Age:</h2>
<input
type="number"
value={age}
onChange={(e) => setAge(e.target.value)}
/>
<p>Your age is: {age}</p>
</div>
);
}
export default Age;
Output:
How Controlled Component works in React?
This component is used to handle the form data using React state. It supports a predictable and efficient way to handle the form user input details. Here are some of the reasons that are shown below in detail:
1) Manage the user input with event handlers:
With the use of Event handlers, you can easily manage the form inputs. The onchange event is used for triggering the handleChange function, which modifies the state in the component.
Example
Code:
function Age({ value, setValue }) {
const handleChange = (event) => {
setValue(event.target.value);
};
return (
<form>
<label>
Age:
<input type="number" value={value} onChange={handleChange} />
</label>
</form>
);
}
2) Modify the State in a Parent Component:
With the use of the setValue function, you can modify the state in a parent component. It helps the parent component to re-render the child component using the new state value.
Example
Code:
function Email({ value, setValue }) {
const handleChange = (event) => {
setValue(event.target.value);
};
return (
<form>
<label>
Email:
<input type="email" value={value} onChange={handleChange} />
</label>
</form>
);
}
3) Assigning value as props:
You can easily send data from parent to child components with the help of using props. It helps for managing the child component to show the state and also update it.
Example
Code:
import React, { useState } from 'react';
function AgeInput({ age, setAge }) {
return (
<div>
<label>
Age:
<input
type="number"
value={age}
onChange={(e) => setAge(e.target.value)}
/>
</label>
</div>
);
}
function ParentComponent() {
const [age, setAge] = useState('');
return (
<div>
<h2>Controlled Component Example with Age</h2>
<AgeInput age={age} setAge={setAge} />
<p>Your Age: {age}</p>
</div>
);
}
export default ParentComponent;
Advantages of Controlled Component
This component provides many advantages, which are as follows:
1) Real-time Validation:
This component helps to provide real-time feedback to users and interact with the real-time validation. You can verify whether the user gives all the correct details or not.
2) Single Source of Truth:
In this component, react state manages the value of the user input. This provides data consistency because it doesn't use the DOM element.
3) Integrate with Complex UI libraries:
This component can be easily integrated with complex libraries and frameworks like Formik for managing the form and Redux for managing state management.
Disadvantages of Controlled Component
1) Performance Overhead:
With the use of keystrokes, you can easily update the React state. This component gives you more re-renders of the component.
2) More complexity and Boilerplate:
Controlled components use more code to manage the state with useState, changing the value using the props. More controlled inputs require a greater number of states to make the component difficult to manage.
Uncontrolled Component:
With the use of this component, you cannot directly manage the form element with the React State. But we can handle its own state and interact through the references. This component is beneficial for managing the simple forms and file uploads, and can be accessed through the DOM elements.
Syntax:
import React, { useRef } from "react";
function UncontrolledComponent() {
const inputRef = useRef();
const showValue = () => {
alert("Your Age: " + inputRef.current.value);
};
return (
<div>
<input type="number" ref={inputRef} placeholder="Enter age" />
<button onClick={showValue}>Show</button>
</div>
);
}
export default UncontrolledComponent;
Example
Code:
import React, { useRef } from "react";
function UncontrolledExample() {
const maleRef = useRef();
const femaleRef = useRef();
const handleSubmit = () => {
let selected = "";
if (maleRef.current.checked) {
selected = "Male";
} else if (femaleRef.current.checked) {
selected = "Female";
} else {
selected = "None selected";
}
alert("Selected Gender: " + selected);
};
return (
<div>
<label>
<input type="radio" name="gender" ref={maleRef} /> Male
</label>
<br />
<label>
<input type="radio" name="gender" ref={femaleRef} /> Female
</label>
<br />
<button onClick={handleSubmit}>Submit</button>
</div>
);
}
export default UncontrolledExample;
Output:
How Uncontrolled Component works in React?
This component is used to handle the form using the DOM elements, like refs, to access the element directly. Here are some of the reasons that are shown below in detail:
1) Easily Access with the useRef Hook:
With the use of the useRef Hook, you can easily create a mutable reference and handle it across renders.
Example
Code:
import React, { useRef } from 'react';
function UncontrolledName(){
const nameRef = useRef();
const showName = () => {
alert(nameRef.current.value);
};
return (
<div>
<input type="text" ref={nameRef} />
<button onClick={showName}>Show</button>
</div>
);
}
export default UncontrolledName;
2) Handle the value on Submit:
You can use the useRef hook in order to manipulate the input value. It ensures how to change the state without using the React state. And, onClick events perform all the events on the submit button.
Example
Code: