Loading

Quipoin Menu

Learn • Practice • Grow

react / Uncontrolled Components
tutorial

Uncontrolled Components

While controlled components are the React way of handling forms, there's an alternative approach called **uncontrolled components**. In this approach, the DOM itself maintains the form data, and you use `refs` to access values when needed.

What is an Uncontrolled Component?

In an uncontrolled component, form inputs maintain their own state internally (like traditional HTML). React doesn't control the value instead, you use a `ref` to get the value from the DOM when you need it, such as on form submission.

Uncontrolled components are useful when you're integrating React with non-React code or when you want less code for simple forms. However, controlled components are generally recommended.

Basic Uncontrolled Input with useRef
import React, { useRef } from 'react';

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

  function handleClick() {
    alert('Input value: ' + inputRef.current.value);
  }

  return (
    <div>
      <input
        type="text"
        ref={inputRef}
        defaultValue="Initial value"
      />
      <button onClick={handleClick}>Show Value</button>
    </div>
  );
}

Notice we use `defaultValue` instead of `value`. This sets the initial value, but after that, the input manages its own state.

Uncontrolled Form Submission
function UncontrolledForm() {
  const nameRef = useRef(null);
  const emailRef = useRef(null);

  function handleSubmit(event) {
    event.preventDefault();
    const formData = {
      name: nameRef.current.value,
      email: emailRef.current.value
    };
    console.log('Form submitted:', formData);
  }

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label>
          Name:
          <input
            type="text"
            ref={nameRef}
            defaultValue=""
          />
        </label>
      </div>
      <div>
        <label>
          Email:
          <input
            type="email"
            ref={emailRef}
            defaultValue=""
          />
        </label>
      </div>
      <button type="submit">Submit</button>
    </form>
  );
}

Uncontrolled File Input

File inputs are always uncontrolled because their value is read-only and set by the user. This is one case where uncontrolled components are actually required.
function FileUpload() {
  const fileRef = useRef(null);

  function handleUpload() {
    const file = fileRef.current.files[0];
    if (file) {
      console.log('Selected file:', file.name);
    }
  }

  return (
    <div>
      <input
        type="file"
        ref={fileRef}
      />
      <button onClick={handleUpload}>Upload</button>
    </div>
  );
}

When to Use Uncontrolled Components

  • File Inputs: Always uncontrolled (React can't set file input values for security).
  • Simple Forms: When you only need values on submission and don't need real-time validation.
  • Integrating with Non-React Code: When working with libraries that manipulate the DOM directly.
  • Performance: For very large forms with hundreds of fields (though this is rare).

Controlled vs Uncontrolled Comparison

AspectControlledUncontrolled
State locationReact stateDOM
Value access`value` prop`ref.current.value`
Initial value`value` prop`defaultValue`
Real-time validationEasyMore complex

Two Minute Drill

  • Uncontrolled components let the DOM handle form state you use `refs` to access values when needed.
  • Use `defaultValue` (not `value`) to set initial values in uncontrolled inputs.
  • File inputs must be uncontrolled React cannot set file input values.
  • Controlled components are generally preferred, but uncontrolled components have their use cases.
  • The `useRef` hook is essential for working with uncontrolled components.

Need more clarification?

Drop us an email at career@quipoinfotech.com