React Controlled Vs Uncontrolled Components Complete Guide

 Last Update:2025-06-22T00:00:00     .NET School AI Teacher - SELECT ANY TEXT TO EXPLANATION.    6 mins read      Difficulty-Level: beginner

Understanding the Core Concepts of React Controlled vs Uncontrolled Components

React Controlled vs Uncontrolled Components

Controlled Components

A controlled component in React is a component where the form data is handled by the state of the component. Typically, this means that every change made by the user in an input field is reflected in the component’s state, and the state updates the input field’s value accordingly. This alignment of the input value with the state ensures a single source of truth.

Key Characteristics:

  • State Management: Uses React's state to manage the input values.
  • Live Updates: Each keystroke typically triggers an update in the input value.
  • Validation: Easier to implement validations and formatting as the data is controlled by the state.

Example of a Controlled Component:

import React, { useState } from 'react';

function ControlledComponent() {
  const [inputValue, setInputValue] = useState('');

  const handleChange = (event) => {
    setInputValue(event.target.value);
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    console.log('Controlled Input Value:', inputValue);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input type="text" value={inputValue} onChange={handleChange} />
      <button type="submit">Submit</button>
    </form>
  );
}

export default ControlledComponent;

Explanation:

  • useState Hook: Initializes and manages the inputValue state.
  • handleChange Function: Updates the state based on the input’s onChange event.
  • handleSubmit Function: Prevents the default form submission to manage the submission process programmatically.

Advantages:

  • Validation and Formatting: Easier to enforce validations and apply formatting rules.
  • Real-Time Feedback: Immediate feedback for user inputs can enhance UX.
  • Predictable State: The state fully controls the input, making it predictable and easier to debug.

Disadvantages:

  • Boilerplate Code: Requires more code for simple form inputs.
  • Performance Overhead: For complex forms, the constant state updates can introduce performance overhead.

Uncontrolled Components

An uncontrolled component, on the other hand, does not synchronize the input’s value with any React state. The input’s state is handled by the DOM itself, making it more like traditional HTML forms. In React, you can access the input’s value using a ref, which is a reference to the actual DOM node.

Key Characteristics:

  • DOM Management: Input values are managed by the DOM, not by React state.
  • Minimal State Handling: Reduces the need for state management in some scenarios.
  • Immediate Access: Access to input values is simpler via a ref.

Example of an Uncontrolled Component:

import React, { useRef } from 'react';

function UncontrolledComponent() {
  const inputRef = useRef(null);

  const handleSubmit = (event) => {
    event.preventDefault();
    console.log('Uncontrolled Input Value:', inputRef.current.value);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input type="text" ref={inputRef} />
      <button type="submit">Submit</button>
    </form>
  );
}

export default UncontrolledComponent;

Explanation:

  • useRef Hook: Creates a ref object that directly references the input DOM element.
  • handleSubmit Function: Accesses the input value via inputRef.current.value upon form submission.

Advantages:

  • Simplicity: Less boilerplate code, making it simpler for basic forms.
  • Performance: Generally offers better performance as it avoids unnecessary state updates.
  • Traditional Approach: Mirrors traditional HTML form handling, making it easier for developers familiar with standard form handling practices.

Disadvantages:

  • Limited Control: Harder to enforce real-time validations and formatting.
  • Complex State Management: Detached from React state, making it harder to track user interactions and changes.
  • Asynchronous Access: Input values are only accessible when needed, leading to potential async issues in complex scenarios.

Conclusion

Choosing between controlled and uncontrolled components in React depends on the specific requirements and complexity of the form. For simpler, quick forms with minimal interactivity, uncontrolled components are often sufficient and easier to implement. However, for more complex forms that require real-time validation, formatting, and user feedback, controlled components provide a more robust and flexible approach.

Online Code run

🔔 Note: Select your programming language to check or run code at

💻 Run Code Compiler

Step-by-Step Guide: How to Implement React Controlled vs Uncontrolled Components

Controlled Components

In a controlled component, the form data is handled by the state within the component. The React component manages the state and updates it through user input via setState().

Uncontrolled Components

In an uncontrolled component, the form data is handled by the DOM itself. You use refs to get the value of the form elements from the DOM instead of using the component's state.

Let's walk through some complete examples for both types of components step by step.


Example of a Controlled Component

Step 1: Setting Up the Initial State

First, let's define the initial state for our input field.

import React, { useState } from 'react';

const ControlledComponent = () => {
  const [inputValue, setInputValue] = useState('');

  return (
    <div>
      <h1>Controlled Component Example</h1>
      <input
        type="text"
        value={inputValue}
        onChange={(e) => setInputValue(e.target.value)}
      />
      <p>You typed: {inputValue}</p>
    </div>
  );
};

export default ControlledComponent;

Explanation:

  • State Initialization: We start by defining a state variable inputValue using the useState hook and set an initial value of an empty string.
  • Input Element: The input tag has a value attribute bound to the state inputValue.
  • Event Handling: The onChange event handler updates the state with the latest input value each time the user types.

Example of an Uncontrolled Component

Step 1: Using Refs to Access DOM Elements

We'll use a ref to get the value of an input field directly from the DOM.

Top 10 Interview Questions & Answers on React Controlled vs Uncontrolled Components

Top 10 Questions and Answers: React Controlled vs Uncontrolled Components

1. What are Controlled Components in React?

2. What are Uncontrolled Components in React?

Answer: Uncontrolled Components are those whose values are controlled by the DOM itself. With uncontrolled components, you use a ref to get the form values from the DOM. Unlike controlled components, you don't need an event handler for every update; the value is fetched when needed (often, after form submission).

3. Why would you use Controlled Components?

Answer: Controlled components offer a more direct and controlled approach to form state management, which can provide features like immediate form validation, disabling or enabling buttons, and validating input conditions before submission. They also allow for easy manipulation and synchronization of form state across the UI.

4. Why would you use Uncontrolled Components?

Answer: Uncontrolled components are often faster and simpler to implement since you don’t need to manage and update form state explicitly. They are particularly useful in scenarios where the values are only required after form submission, such as in simple forms that don’t require complex validation or conditional behavior.

5. How do you make a Controlled Component in React?

Answer: Creating a controlled component involves setting up a state variable that holds the value of the input, and then setting the input’s value attribute to this state. You also add an onChange handler to update the state when the input changes. Here’s a simple example:

class ControlledComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = { value: '' };
    }

    handleChange = (event) => {
        this.setState({ value: event.target.value });
    }

    render() {
        return (
            <input
                type="text"
                value={this.state.value}
                onChange={this.handleChange} />
        );
    }
}

6. How do you make an Uncontrolled Component in React?

Answer: To make an uncontrolled component, you use a ref to interact with the form elements directly. You generally fetch the value from the form element when needed, typically upon form submission. Here’s an example:

class UncontrolledComponent extends React.Component {
    constructor(props) {
        super(props);
        this.inputRef = React.createRef();
    }

    handleSubmit = (event) => {
        event.preventDefault();
        console.log(this.inputRef.current.value);
    }

    render() {
        return (
            <form onSubmit={this.handleSubmit}>
                <input
                    type="text"
                    ref={this.inputRef} />
                <button type="submit">Submit</button>
            </form>
        );
    }
}

7. Can you use both Controlled and Uncontrolled Components in the Same Form?

Answer: Yes, you can certainly use both types of components within the same form. This might be useful if some inputs need immediate validation or should be tightly controlled by state, while others remain simple and only send their values at submission.

8. What are the advantages of Controlled Components?

Answer: The main advantages of controlled components are:

  • Immediate UX Updates: You can immediately respond to input changes.
  • Form Validation: Perform validation immediately on input without submitting the form.
  • Conditional UI: Easily change other UI elements based on form inputs.

9. What are the advantages of Uncontrolled Components?

Answer: The primary advantages of uncontrolled components include:

  • Simplicity: Easier and quicker to implement.
  • Performance: No need to manage state changes for component rendering.
  • Interoperability: Better for integrating with third-party libraries or legacy form components that are not designed with controlled components in mind.

10. Which type should you choose for your form?

Answer: The choice between controlled and uncontrolled components largely depends on your form requirements. If you need sophisticated form validation, real-time input checks, or highly synchronized form behavior, controlled components are more suitable. For simple form submissions where input validation is minimal or unnecessary, uncontrolled components offer a simpler approach. In some cases, a mix of both can provide the best solution.

You May Like This Related .NET Topic

Login to post a comment.