FrontendDeveloper.in

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,

  1. Initialize the state using useState hooks in function components or inside constructor for class components.
  2. Set the value of the form element to the respective state variable.
  3. Create an event handler(onChange) to handle the user input changes through useState's updater function or setState from class component.
  4. 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.
Back to all React questions
Get LinkedIn Premium at Rs 399