DEV Community

Cover image for Controlled vs Uncontrolled Components in React
Manikandan K
Manikandan K

Posted on

1

Controlled vs Uncontrolled Components in React

Controlled vs Uncontrolled Component
Controlled Component:

  • In a controlled component, form data is handled by a React component - (state)
  • The internal state (not react state) is not maintained.
  • Validation is easy.
  • Controlled by the parent component.
import React, { useState } from 'react';

const ControlledComponent = () => {
    const [name, setName] = useState("");
    const handleChange = (e) => {
        setName(e.target.value)
    };

    const handleSubmit = () => {
        alert(name)
    }

    return (
        <>
            <form onSubmit={handleSubmit}>
                <label>Name</label>
                <input type="text" value={name} onChange={handleChange} />
                <button type='submit'>Submit</button>
            </form>
        </>
    )
}

export default ControlledComponent
Enter fullscreen mode Exit fullscreen mode

Uncontrolled Component:

  • Uncontrolled component, form data is handled by a DOM Element - (ref)
  • Internal state maintained.
  • Validation is much more complex.
  • Controlled by DOM itself.
import React, { useRef } from 'react'

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

    const handleSubmit = () => {
        alert(inputRef.current.value)
    }

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

export default UncontrolledComponent

Enter fullscreen mode Exit fullscreen mode

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (1)

Collapse
 
vishva123 profile image
Vishva

Can you explain what here meant by internal state

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Retry later