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

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

Top comments (1)

Collapse
 
vishva123 profile image
Vishva

Can you explain what here meant by internal state

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay