Sobes.tech
Middle

Can you give an example where uncontrolled input can be used instead of controlled?

sobes.tech AI

Answer from AI

Uncontrolled input in React is when the value of a form field is managed by the DOM itself, rather than the component's state. This approach can be used when constant control over user input is not required, for example, in simple forms or when minimizing re-renders.

Example of using uncontrolled input:

function NameForm() {
  const inputRef = React.useRef(null);

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

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

Here, the value of the field is not stored in the state but is accessed directly from the DOM via ref when submitting the form. This approach is convenient if you do not need to react to every change in input, reducing the load on the component.

Can you give an example where uncontrolled input can… - sobes.tech