A controlled component is a React component that fully manages the form element's state(e.g, elements like
,<input>
, or<textarea>
)) 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.<select>
The controlled components will be implemented using the below steps,
- Initialize the state using
hooks in function components or inside constructor for class components.useState - Set the value of the form element to the respective state variable.
- Create an event handler(
) to handle the user input changes throughonChange
's updater function oruseState
from class component.setState - 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
event handler as below,handleChange
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.