ReactJS

    Controlled vs. Uncontrolled Components in React: When to Use Each


    Introduction

    The two types of components describing form input processing in React.js are the Controlled and Uncontrolled Components. They are briefly described below.

     

    Controlled Components

    • Definition: Controlled Components are those where the state of a React component controls the form data.
    • How it works: The component uses the useState hook (or other state management techniques) to monitor and update the inputs' values.

     

    import { useState } from "react";const ControlledInput = () => { const [inputValue, setInputValue] = useState(""); return ( <input type="text" value={inputValue} onChange={(e) => setInputValue(e.target.value)} /> );};

     

    Uncontrolled Components

    • Definition: The form data is managed by the DOM itself, not React state.
    • How it works: You call useRef to access the input's value whenever you need to
    import { useRef } from "react";const UncontrolledInput = () => { const inputRef = useRef(); const handleSubmit = () => { alert(`Input Value: ${inputRef.current.value}`); }; return ( <> <input type="text" ref={inputRef} /> <button onClick={handleSubmit}>Submit</button> </> );};

     

    When to Use Which?

    • Use Controlled Components to handle dynamic fields and validation and advanced forms.
    • Use Uncontrolled Components for simple forms or where only performance is the issue.

     

    Ready to transform your business with our technology solutions? Contact Us today to Leverage Our ReactJS Expertise.

    Share

    facebook
    LinkedIn
    Twitter
    Mail
    React

    Related Center Of Excellence