logo
Published on

Controlled and Uncontrolled Components in React

Authors
  • avatar
    Name
    Ganesh Negi
    Twitter

Controlled and Uncontrolled Components in ReactJs

In React, components that manage their own state and handle user input changes within React’s ecosystem are known as controlled components. These components maintain their form data within the React state and update their values dynamically using event handlers like onChange and setState().

Controlled and Uncontrolled Components in
ReactJs

Understanding Controlled Components

When working with forms in React, you typically use standard HTML elements such as input, textarea, and select. However, in controlled components, React takes over the responsibility of managing the form elements' state. This means that rather than letting the DOM handle user inputs, React controls them through state variables.

Since controlled components use React state as the single source of truth, they ensure consistency and predictability. Any modifications to input values trigger an onChange event, which updates the state and forces the component to re-render with the latest data.

Example: Controlled Component in React

import { useState } from "react";

function App() {
    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");

    const handleSubmit = (event) => {
        event.preventDefault();
        console.log("Email:", email);
        console.log("Password:", password);
    };

    return (
        <form onSubmit={handleSubmit}>
            <input
                type="email"
                name="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                required
            />
            <input
                type="password"
                name="password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                required
            />
            <button type="submit">Submit</button>
        </form>
    );
}

How Controlled Components Work

In the above example, the input values are directly linked to React state variables (email and password). As users enter data, the state updates accordingly, ensuring React always holds the most recent values. This approach offers real-time validation, as form values can be checked against certain conditions with each keystroke.

Advantages of Controlled Components:

Instant feedback: Since values are stored in state, you can validate them as users type. Single source of truth: React maintains and updates the state, ensuring consistency. Predictable behavior: Since the data flow is managed within React, debugging and testing become easier.

Understanding Uncontrolled Components

Unlike controlled components, uncontrolled components do not rely on React state to manage form inputs. Instead, they store data within the DOM itself, making them behave similarly to traditional HTML form elements.

How Uncontrolled Components Work

In uncontrolled components, we use Refs (React’s way of referencing DOM elements) to directly access input values when needed. Instead of tracking every keystroke, we retrieve the value only when required—typically upon form submission.

Example: Uncontrolled Component in React

import { useRef } from "react";

function App() {
    const emailRef = useRef();
    const passwordRef = useRef();

    const handleSubmit = (event) => {
        event.preventDefault();
        console.log("Email:", emailRef.current.value);
        console.log("Password:", passwordRef.current.value);
    };

    return (
        <form onSubmit={handleSubmit}>
            <input type="email" name="email" ref={emailRef} required />
            <input type="password" name="password" ref={passwordRef} required />
            <button type="submit">Submit</button>
        </form>
    );
}

Key Characteristics of Uncontrolled Components

No React state management: Input values are stored in the DOM instead of React state. Refs for value retrieval: Instead of handling state updates, refs allow us to fetch input values when required. Less real-time control: Unlike controlled components, validation is usually done after form submission.

Advantages of Uncontrolled Components:

Minimal React involvement: Useful when integrating React with non-React applications or third-party libraries. Lower performance overhead: Since state updates aren’t triggered on every keystroke, they may be more efficient for large forms.

Controlled vs. Uncontrolled Components: Key Differences

Feature

Controlled Components

Data Handling: Managed via React state Event Handling: Uses onChange event handlers Validation: Can validate with each keystroke Performance: Re-renders on every input change Predictability: Highly predictable and testable

Uncontrolled Components

Data Handling: Stored in the DOM Event Handling: Uses refs to fetch values Validation: Typically validated upon submission Performance: More efficient for large forms Predictability: Less predictable, as values may change externally

When to Use Controlled vs. Uncontrolled Components?

Use controlled components when you need real-time validation, form value tracking, or when working on a React-only project. Use uncontrolled components when integrating with third-party libraries or when working on simple forms where React state management is unnecessary. Final Thoughts Both controlled and uncontrolled components offer unique advantages in React. Controlled components provide a structured, predictable approach for handling form inputs, whereas uncontrolled components allow direct DOM interaction for simpler use cases. The best choice depends on the specific requirements of your application—whether you need full React control or prefer a more lightweight, DOM-driven approach.