React question detail
What are controlled components?
A controlled component is a React component that fully manages the form element's state(e.g, elements like <input>, <textarea>, or <select>)) using React's internal state mechanism. i.e, The component does not manage its own internal state — instead, React acts as the single source of truth for form data.
The controlled components will be implemented using the below steps,
- Initialize the state using
useStatehooks in function components or inside constructor for class components. - Set the value of the form element to the respective state variable.
- Create an event handler(
onChange) to handle the user input changes throughuseState's updater function orsetStatefrom class component. - Attach the above event handler to form element's change or click events
Note: React re-renders the component every time the input value changes.
For example, the name input field updates the username using handleChange event handler as below,
import React, { useState } from "react";
function UserProfile() {
const [username, setUsername] = useState("");
const handleChange = (e) => {
setUsername(e.target.value);
};
return (
<form>
<label>
Name:
<input type="text" value={username} onChange={handleChange} />
</label>
</form>
);
}
In these components, DOM does not hold the actual data instead React does.
Benefits:
- Easy to implement validation, conditional formatting, or live feedback.
- Full control over form data.
- Easier to test and debug because the data is centralized in the component’s state.