DEV Community

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

Posted on

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

Top comments (1)

Collapse
 
vishva123 profile image
Vishva

Can you explain what here meant by internal state