DEV Community

Fatima Alam
Fatima Alam

Posted on

React Controlled Components V/S Uncontrolled Components

Controlled Components

Image description

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

    function onSubmit() {
        console.log("Email value: " + email);
        console.log("Password value: " + password);
    }


    return (
        <form onSubmit={onSubmit}>
            <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
            />
            <input type="submit" value="Submit" />
        </form>
    );
}
Enter fullscreen mode Exit fullscreen mode

The email input element value is held by the email state. When the email value is being changed in the form by the user, the onChange event handle associated with the email input field will be triggered and all the changes will be handled using the setNamemethod.

The instant validation check is one of the major benefits of using the controlled component over the uncontrolled component in react.

You can have validation checks on every keystroke of the user when using controlled components in react. This is because we can access the input value at every time with the help of react state, whereas, in an uncontrolled component, the input value is only available when the form is submitted by the user. For example, we can perform a validation check on the user input (password type) where the requirement is that the input password should be at least eight characters and display a conditional message accordingly.

Uncontrolled Components

Image description

function App() {
    function onSubmit() {
        console.log("Email value: " + window.email.value);
        console.log("Password value: " + window.password.value);
    }

    return (
        <form onSubmit={onSubmit}> 
            <input type="email" name="email" id="email" required />
            <input type="password" name="password" id="password" required />
            <input type="submit" value="Submit" />
        </form>
    );
}
Enter fullscreen mode Exit fullscreen mode

In this case we have created ids to keep a check on the data of this field so now no state is maintained and the check is done only when it is submitted so there is a check on the dom.

We can also use Refs which acts as pointers to DOM elements.

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

    function onSubmit() {
        console.log("Email value: " + window.email.value);
        console.log("Password value: " + window.password.value);
    }

    return (
        <form onSubmit={onSubmit}>
            <input type="text" name="name" ref={nameRef} required />
            <input type="email" name="email" ref={emailRef} required />
            <input type="submit" value="Submit" />
        </form>
    );
}
Enter fullscreen mode Exit fullscreen mode

What to use?
According to the official react documentation, the easiest way for us to build simple and reusable components is by using the controlled components. The controlled components provide a higher abstraction layer to work on. Hence we do not need to work on handling every element using DOM API. This reduces the cognitive effort needed to mentally understand the code and also works while building the real application and the related unit tests.

On the other hand, if you are working on a complex project which requires you to integrate react with libraries that do not follow React’s design pattern, then working directly with DOM API will help us more. Also, the uncontrolled components are harder to main and test. Hence both options have their valid cases, and we can use those according to our needs.

Difference
Image description

Conclusion
React supports two ways to handle the form data; it can either be a Controlled component or an Uncontrolled component.
React provides two distinctively flexible solutions, i.e., model-view (controlled) and only-view (uncontrolled).
Controlled components have a one-way data flow where the state inside the component serves as the single source of truth.
The parent component has held over the form data in the controlled component.
The DOM itself handles all the form data in an uncontrolled component.
It can become cumbersome to work with controlled components if there are many input fields on the page.
Controlled component react provides validation benefits on every keystroke of the user.
All the state changes in a controlled component are made with the help of the setState() method.
An uncontrolled component stores the current value of the form data using react ref.
Uncontrolled component react are helpful when we need to integrate react with other libraries which do not follow react design patterns.

Top comments (0)