DEV Community

Stanley
Stanley

Posted on • Updated on

Difference between controlled components and uncontrolled components in Reactjs

I - Controlled components

In controlled components, the form data is handled by React components, and it is recommended to use controlled components to implement forms.

Example:

import React, { useState } from 'react'

export default function ControlComponent() {
  const [state, setState] = useState({
    value: ''
    })

    const handleChange =(event)=> {
      setState({value: event.target.value});
     }

    const handleSubmit = (event)=> {
    alert('A name was submitted: ' + state.value);
    event.preventDefault();
    }

    return (
    <form onSubmit={handleSubmit}>
            <label>
              Name:
              <input type="text" value={state.value} onChange={handleChange} />
            </label>
            <input type="submit" value="Submit" />
          </form>
    );

}
Enter fullscreen mode Exit fullscreen mode

II- Uncontrolled components

In uncontrolled components, the form data is handled by the DOM itself.
Instead of writing an event handler for every state update, you can use useRef to get form values from the DOM.

Example:

import React, {useRef} from 'react'

export default function UnControlledComponent() {
  const inputElement = useRef(null);

  const handleSubmit =(event)=> {
     alert('A name was submitted: ' + inputElement.current.value);
     event.preventDefault();
   }

     return (
       <form onSubmit={handleSubmit}>
         <label>
           Name:
           <input type="text" ref={inputElement} />
         </label>
         <input type="submit" value="Submit" />
       </form>
     );
}

Enter fullscreen mode Exit fullscreen mode

Discussion (1)