DEV Community

Matin Imam
Matin Imam

Posted on

Controlled & Uncontrolled Inputs

Controlled and Uncontrolled inputs are terms used in the context of form inputs in web development, especially in frameworks like React.

Controlled Inputs

In controlled inputs, the value of the input field is controlled by the component’s state. This means that the component’s state holds the current value of the input, and when the input value changes (e.g., through user typing), it updates the state, and the input value reflects the state. This is typically done by setting the input’s value prop to the state value and providing an onChange handler to update the state when the input changes. Controlled inputs are commonly used in React applications for form handling.

import React, { useState } from 'react';

function ControlledInputExample() {
  const [inputValue, setInputValue] = useState('');

  const handleChange = (e) => {
    setInputValue(e.target.value);
  };

  return (
    <input
      type="text"
      value={inputValue}
      onChange={handleChange}
    />
  );
}
Enter fullscreen mode Exit fullscreen mode

Uncontrolled Inputs

In uncontrolled inputs, the input field’s value is not directly controlled by React state. Instead, the input element manages its own state internally. This means that React doesn’t have direct control over the input value, and to get the value, you typically have to access the DOM directly (e.g., using refs) rather than querying React state. Uncontrolled inputs are less common in React but can be useful in certain situations, such as for handling complex form behaviors or integrating with non-React libraries that manage input state differently.

import React, { useRef } from 'react';

function UncontrolledInputExample() {
  const inputRef = useRef(null);

  const handleClick = () => {
    console.log(inputRef.current.value);
  };

  return (
    <div>
      <input type="text" ref={inputRef} />
      <button onClick={handleClick}>Get Value</button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

In summary, controlled inputs tie the input value directly to React state, providing more control and synchronization between the UI and state. Uncontrolled inputs are managed internally by the DOM or other libraries, with React accessing their values indirectly when needed.

Top comments (0)