Home >Web Front-end >JS Tutorial >Controlled vs Uncontrolled Components in React

Controlled vs Uncontrolled Components in React

Patricia Arquette
Patricia ArquetteOriginal
2024-12-19 15:59:10381browse

Controlled Components: React Components that control the state of form elements via state or props, i.e., every state mutation will have an associated handler function.

Characteristics

  • Value controlled by state - element value is bound to state variable
  • Requires event handler - To update the state you need event handler
  • Predictable - Since the component state represents the input value, the component is predictable and easy to debug
  • React Handles the input data and doesn't rely on DOM to keep track of the current input value
import React, { useState } from 'react';

function ControlledForm() {
  const [value, setValue] = useState('');

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

  return (
    <form>
      <input 
        type="text" 
        value={value} 
        onChange={handleChange} 
      />
    </form>
  );
}

Uncontrolled Components: React Component where DOM itself handles the form element's state. React accesses the input value via ref, which stores its own state internally, and you query the DOM using a ref to find its current value when you need it. This is a bit more like traditional HTML.

Characteristics

  • Value controlled by DOM - The input field's value is not bound to a state variable.
  • Uses Ref to access a value or to get the value of input element when needed
  • They are simpler to set up if you don't need real-time control over input.
  • Suitable for scenarios where react state isn't required to control the input.
import React, { useRef } from 'react';

function UncontrolledForm() {
  const inputRef = useRef();

  const handleSubmit = (event) => {
    event.preventDefault();
    alert('Input Value: ' + inputRef.current.value);
  };

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

Here's a comparison table between controlled and uncontrolled components:
Controlled vs Uncontrolled Components in React

When to use when
Controlled - for real-time validations, input formatting, or immediate feedback.
Uncontrolled - used for simple use cases like file uploads pre-filled form value isn't frequent or needs to be deferred until form submission.

The above is the detailed content of Controlled vs Uncontrolled Components in React. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn