Popular Searches
Popular Course Categories
Popular Courses

Uncontrolled Components

Uncontrolled Components

React Forms

Uncontrolled Components in React JS

Course: React JS Training | Topic: Uncontrolled Components

Learning Objective: In this lesson, you will learn what uncontrolled components are, how they work, how to access form values using refs, how to use default values, and how to build forms with uncontrolled inputs in React.


1. Introduction to Uncontrolled Components

In React, uncontrolled components are form elements whose current values are managed primarily by the browser's DOM rather than by React state. React can provide an initial value, but it does not control every change to the input.

To read the current value of an uncontrolled input, developers commonly use the useRef() Hook to access the DOM element when needed, such as when a form is submitted.

Common uncontrolled form elements include text inputs, textareas, select elements, checkboxes, radio buttons, and file inputs. File inputs are a special case because their selected file value cannot be set programmatically in the usual way.

Example of an Uncontrolled Input

function NameForm() {
  return (
    <form>
      <label htmlFor="username">Enter your name:</label>
      <input id="username" name="username" defaultValue="Manish" />
      <button type="submit">Submit</button>
    </form>
  );
}
export default NameForm;

Explanation: The defaultValue="Manish" property sets the initial input value. After the component mounts, the user can change the text without React state controlling every keystroke.


2. What Is an Uncontrolled Component?

An uncontrolled component is a React form element that maintains its current input value in the DOM. React may provide an initial value through properties such as defaultValue or defaultChecked, but the DOM manages subsequent user changes.

Key Characteristics

  • The browser DOM maintains the current form value.
  • React does not need to store every input change in state.
  • The useRef() Hook can provide access to the input element.
  • Values can be read when needed, particularly during form submission.
  • Uncontrolled inputs can be useful for simple forms and file uploads.
  • Changing a defaultValue after mounting does not automatically reset the current input value.

Basic Syntax

import { useRef } from "react";

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

  function handleSubmit(event) {
    event.preventDefault();
    console.log(inputRef.current.value);
  }

  return (
    <form onSubmit={handleSubmit}>
      <input ref={inputRef} defaultValue="Hello React" />
      <button type="submit">Submit</button>
    </form>
  );
}
export default Example;

In this example, inputRef.current refers to the actual input element after React has mounted it. Its value property contains the text currently entered by the user.


3. How Uncontrolled Components Work

Uncontrolled components follow a simple process. React renders the form element, the browser manages its current value, and a ref allows the application to read that value when required.

  1. Render the input: React creates an HTML form element.
  2. Set an initial value: Use defaultValue or defaultChecked if necessary.
  3. Enter data: The user types or selects a value, and the browser updates the DOM.
  4. Access the element: A ref points to the DOM node.
  5. Read the value: Use ref.current.value or another suitable DOM property.
  6. Process the data: Validate, display, or submit the collected information.

Working Flow

React Component
      |
      v
Render Uncontrolled Input
      |
      v
Browser DOM Manages Value
      |
      v
User Enters Data
      |
      v
Ref Accesses DOM Element
      |
      v
Read Value on Submit
      |
      v
Validate or Process Data

4. Understanding Refs in React

A ref is a reference object that lets a React component access a DOM element or retain a value without triggering a re-render when the ref's current property changes. For uncontrolled forms, refs are commonly used to read the current values of input elements.

Using the useRef() Hook

import { useRef } from "react";

function App() {
  const nameRef = useRef(null);

  function showName() {
    alert(nameRef.current.value);
  }

  return (
    <div>
      <input ref={nameRef} placeholder="Enter your name" />
      <button type="button" onClick={showName}>
        Show Name
      </button>
    </div>
  );
}
export default App;

Explanation of the Code

  • useRef(null) creates a ref whose initial value is null.
  • ref={nameRef} connects the ref to the input DOM element.
  • nameRef.current provides access to that element after it mounts.
  • nameRef.current.value reads the current input text.
  • The button calls showName() to display the entered name.

Important: Check that the referenced element exists before accessing its properties if it might not be mounted. Avoid reading or writing ref.current during rendering when the value is needed to determine the displayed UI; use state for values that should drive rendering.


5. defaultValue in Uncontrolled Components

The defaultValue property sets the initial value of an uncontrolled text input, textarea, or select element. It does not make React control the current value after the user begins interacting with the element.

Example

function ProfileForm() {
  return (
    <form>
      <label htmlFor="fullName">Full Name:</label>
      <input
        id="fullName"
        name="fullName"
        defaultValue="Rahul Sharma"
      />
    </form>
  );
}
export default ProfileForm;

When the form first appears, the input displays Rahul Sharma. The user can replace that value directly. Changing the defaultValue prop on a later render does not normally update the already-mounted input's current value.

defaultValue vs value

Property Purpose Typical Usage
defaultValue Specifies the initial value Uncontrolled input
value Specifies the current value React controls Controlled input, normally with an onChange handler

6. Using defaultChecked for Checkboxes and Radio Buttons

For uncontrolled checkboxes and radio buttons, use defaultChecked to specify their initial selected state. The browser then manages changes made by the user.

Checkbox Example

function TermsForm() {
  return (
    <label>
      <input
        type="checkbox"
        name="terms"
        defaultChecked={false}
      />
      I agree to the terms and conditions
    </label>
  );
}
export default TermsForm;

Radio Button Example

function GenderForm() {
  return (
    <fieldset>
      <legend>Select an option</legend>
      <label>
        <input
          type="radio"
          name="gender"
          value="male"
          defaultChecked={true}
        />
        Male
      </label>
      <label>
        <input
          type="radio"
          name="gender"
          value="female"
        />
        Female
      </label>
    </fieldset>
  );
}
export default GenderForm;

Radio buttons belonging to the same group should share the same name. The browser uses this name to manage the group's selection behavior.


7. Reading Form Values Using Multiple Refs

When a form contains several uncontrolled inputs, you can create a separate ref for each element and read all values when the form is submitted.

Example: Contact Form

import { useRef } from "react";

function ContactForm() {
  const nameRef = useRef(null);
  const emailRef = useRef(null);
  const messageRef = useRef(null);

  function handleSubmit(event) {
    event.preventDefault();

    const contactData = {
      name: nameRef.current.value.trim(),
      email: emailRef.current.value.trim(),
      message: messageRef.current.value.trim()
    };

    console.log(contactData);
  }

  return (
    <form onSubmit={handleSubmit}>
      <label htmlFor="name">Name:</label>
      <input id="name" name="name" ref={nameRef} required />

      <label htmlFor="email">Email:</label>
      <input id="email" name="email" type="email" ref={emailRef} required />

      <label htmlFor="message">Message:</label>
      <textarea id="message" name="message" ref={messageRef} required />

      <button type="submit">Send Message</button>
    </form>
  );
}
export default ContactForm;

What Happens Here?

  • Three refs point to the name, email, and message elements.
  • The submit handler prevents the browser's default form navigation.
  • The current values are read from the DOM and trimmed to remove surrounding whitespace.
  • The collected data is grouped into a JavaScript object.
  • The object is logged for demonstration; a real application can send validated data to a server.

8. Using FormData with Uncontrolled Forms

For standard HTML forms, the browser's FormData API can collect values from named form controls. This can reduce the need to create a separate ref for every input.

Example

function RegistrationForm() {
  function handleSubmit(event) {
    event.preventDefault();

    const formData = new FormData(event.currentTarget);
    const data = Object.fromEntries(formData.entries());

    console.log(data);
  }

  return (
    <form onSubmit={handleSubmit}>
      <input name="username" placeholder="Username" required />
      <input name="email" type="email" placeholder="Email" required />
      <button type="submit">Register</button>
    </form>
  );
}
export default RegistrationForm;

Important notes:

  • Controls generally need a name attribute to be included in form data.
  • Unchecked checkboxes and radio buttons are not included as selected values.
  • File inputs produce file objects in FormData.
  • Repeated field names may produce multiple entries; use formData.getAll(name) when appropriate.
  • Object.fromEntries() keeps only one value for repeated keys, so it is not suitable by itself for every multi-value form.

9. Handling File Inputs in React

A file input is a common example of an uncontrolled element. The browser controls which file the user selects, and React cannot set an arbitrary local file path through the input's value property.

Example: File Upload

import { useRef } from "react";

function FileUpload() {
  const fileRef = useRef(null);

  function handleSubmit(event) {
    event.preventDefault();

    const file = fileRef.current.files[0];

    if (!file) {
      alert("Please select a file.");
      return;
    }

    console.log("File name:", file.name);
    console.log("File size:", file.size);
    console.log("File type:", file.type);
  }

  return (
    <form onSubmit={handleSubmit}>
      <label htmlFor="document">Choose a document:</label>
      <input
        id="document"
        name="document"
        type="file"
        ref={fileRef}
        accept=".pdf,.doc,.docx"
      />
      <button type="submit">Check File</button>
    </form>
  );
}
export default FileUpload;

Explanation

  • type="file" lets the user choose a file from their device.
  • accept provides a file-type selection hint; it is not a security guarantee.
  • fileRef.current.files provides the selected file list.
  • files[0] accesses the first selected file.
  • The example reads file metadata but does not upload the file.

Before uploading files, validate file size and allowed types on the client for usability and on the server for security. Never trust client-side validation alone.


10. Complete Practical Project: Student Registration Form

This project demonstrates how to build a student registration form using uncontrolled inputs, refs, browser validation, and form submission handling.

Project Features

  • Collects student name, email, course, and phone number.
  • Uses refs to read input values when submitting.
  • Uses required and appropriate input types for basic browser validation.
  • Displays the collected details after successful submission.
  • Resets the form after submission.

Complete Code

import { useRef, useState } from "react";

function StudentRegistration() {
  const nameRef = useRef(null);
  const emailRef = useRef(null);
  const phoneRef = useRef(null);
  const courseRef = useRef(null);
  const formRef = useRef(null);
  const [student, setStudent] = useState(null);

  function handleSubmit(event) {
    event.preventDefault();

    const name = nameRef.current.value.trim();
    const email = emailRef.current.value.trim();
    const phone = phoneRef.current.value.trim();
    const course = courseRef.current.value;

    if (!name || !email || !phone || !course) {
      alert("Please complete all fields.");
      return;
    }

    setStudent({ name, email, phone, course });
    formRef.current.reset();
  }

  return (
    <div>
      <h2>Student Registration</h2>

      <form ref={formRef} onSubmit={handleSubmit}>
        <label htmlFor="studentName">Student Name:</label>
        <input
          id="studentName"
          name="studentName"
          ref={nameRef}
          required
        />

        <label htmlFor="studentEmail">Email:</label>
        <input
          id="studentEmail"
          name="studentEmail"
          type="email"
          ref={emailRef}
          required
        />

        <label htmlFor="studentPhone">Phone:</label>
        <input
          id="studentPhone"
          name="studentPhone"
          type="tel"
          ref={phoneRef}
          required
        />

        <label htmlFor="course">Choose Course:</label>
        <select
          id="course"
          name="course"
          ref={courseRef}
          defaultValue=""
          required
        >
          <option value="" disabled>Select a course</option>
          <option value="React JS">React JS</option>
          <option value="Flutter">Flutter</option>
          <option value="Selenium">Selenium</option>
        </select>

        <button type="submit">Register Student</button>
      </form>

      {student && (
        <section>
          <h3>Registration Details</h3>
          <p>Name: {student.name}</p>
          <p>Email: {student.email}</p>
          <p>Phone: {student.phone}</p>
          <p>Course: {student.course}</p>
        </section>
      )}
    </div>
  );
}
export default StudentRegistration;

How the Project Works

  1. Each ref connects to one form element.
  2. The browser checks fields marked as required and validates the email input's format.
  3. The submit handler prevents a normal page reload.
  4. The current values are read from the DOM and trimmed where appropriate.
  5. The collected details are stored in React state because they are now used to render the registration summary.
  6. The form is reset to its initial values.

Learning point: An application can use uncontrolled inputs and still use React state for other UI data. The key distinction is that the input values themselves are not continuously controlled by React state.

Production note: This is a learning example. A real registration system should validate data on the server, handle submission errors, protect personal information, and send the details to an appropriate backend or API.


11. Advantages of Uncontrolled Components

  • Less state code: You do not need a state variable and change handler for every input.
  • Simple forms: Useful when values are only needed at submission time.
  • Convenient file access: Works naturally with browser file inputs and the File API.
  • Easy HTML form integration: Can work with native browser form behavior and FormData.
  • Useful for third-party integrations: Refs can help connect React with DOM-based libraries.
  • Initial values are straightforward: Use defaultValue and defaultChecked.

12. Disadvantages of Uncontrolled Components

  • Less immediate access to input state: React does not automatically know about every change to the DOM value.
  • Live validation is less convenient: Real-time feedback may require event handlers or additional logic.
  • Complex interactions are harder: Dependent fields and conditional UI are often easier with controlled inputs.
  • Programmatic updates require care: Updating a ref or DOM value does not automatically cause a React re-render.
  • Testing may need DOM interaction: Tests should simulate user input and form submission realistically.
  • Refs can become difficult to manage: A large form with many refs may be less maintainable than a well-structured controlled form or form library.

13. Controlled vs Uncontrolled Components

Controlled and uncontrolled components are two approaches to handling form data in React. Neither is universally best; choose based on how the form needs to behave.

Feature Controlled Component Uncontrolled Component
Source of current input value React state DOM element
Typical input property value or checked defaultValue or defaultChecked
Reading the value Read state Read the DOM through a ref or FormData
Change handler Usually required to update state Not required just to maintain the input value
Live UI updates from input Easy to implement Requires additional event handling or state
Validation and conditional fields Often easier to coordinate Can require more manual logic
File input Selected files are accessed through the DOM Natural fit for file selection
Good use cases Search, live validation, dependent fields Simple forms, file selection, submit-time reads

Controlled Input Example

import { useState } from "react";

function ControlledInput() {
  const [name, setName] = useState("");

  return (
    <input
      value={name}
      onChange={(event) => setName(event.target.value)}
      placeholder="Enter name"
    />
  );
}

Uncontrolled Input Example

import { useRef } from "react";

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

  function showName() {
    alert(nameRef.current.value);
  }

  return (
    <>
      <input ref={nameRef} placeholder="Enter name" />
      <button type="button" onClick={showName}>Show Name</button>
    </>
  );
}

14. Common Mistakes to Avoid

Mistake 1: Using value When You Want an Uncontrolled Input

// This makes the input controlled by React.
<input value="Hello" />

// For an uncontrolled input with initial text:
<input defaultValue="Hello" />

Use defaultValue if you want to specify only the initial text and allow the browser to manage later changes. A controlled input with a fixed value and no updating handler can become effectively read-only.

Mistake 2: Accessing a Ref Before the Element Exists

const inputRef = useRef(null);

function showValue() {
  if (inputRef.current) {
    console.log(inputRef.current.value);
  }
}

Before the input mounts, inputRef.current may be null. Access the value from a suitable event handler after the element exists.

Mistake 3: Forgetting to Prevent Default Form Submission

function handleSubmit(event) {
  event.preventDefault();
  console.log("Form submitted");
}

Without event.preventDefault(), the browser may perform a normal form submission and navigate or reload the page.

Mistake 4: Forgetting the name Attribute

<input name="email" type="email" />

Give controls a meaningful name when you intend to collect their values with FormData or submit them as regular form fields.

Mistake 5: Expecting defaultValue to Reset the Input on Every Render

defaultValue specifies the initial value; changing it after the input has mounted does not normally replace the current DOM value. To reset an uncontrolled form, you can use the form's native reset() method or deliberately remount the relevant form when appropriate.

Mistake 6: Assuming Refs Trigger Re-renders

Changing ref.current does not trigger a React re-render. If the entered value must immediately update text, validation messages, filtered results, or other displayed UI, controlled state is often a better choice.


15. Best Practices for Uncontrolled Components

  • Use uncontrolled inputs when you mainly need their values at submission time.
  • Use useRef(null) to reference DOM elements in functional components.
  • Use defaultValue and defaultChecked for initial values.
  • Assign useful name attributes to form controls.
  • Use labels and appropriate input types to improve accessibility and browser validation.
  • Prevent the default form action when handling submission within React.
  • Check for missing elements or values before accessing or processing them.
  • Use controlled components when form state needs to drive UI updates on every change.
  • Do not mix value and defaultValue on the same input to try to control it in two different ways.
  • Validate data on the server as well as on the client when submitting real information.
  • Avoid using refs as a replacement for React state when the value affects rendering.
  • Keep ref usage focused and avoid unnecessary direct DOM manipulation.

16. When Should You Use Uncontrolled Components?

  • Simple contact form: Collect name, email, and message on submit.
  • File upload: Read the selected file through the DOM.
  • Quick data-entry form: Read values only when the user submits.
  • Third-party DOM widget: Integrate with a library that expects direct DOM access.
  • Native form integration: Use FormData to collect named fields.

Choose controlled components when you need live search, instant validation, dependent inputs, conditional field rendering, or other UI behavior that must respond directly to each change in the input.


17. Interview Questions and Answers

Q1. What is an uncontrolled component in React?

Answer: An uncontrolled component is a form element whose current value is managed by the DOM rather than continuously by React state. React can set an initial value, and a ref or FormData can be used to read the current value.

Q2. How do you access an uncontrolled input's value?

Answer: Create a ref with useRef(null), attach it to the input using the ref prop, and read inputRef.current.value in an event handler after the input has mounted.

Q3. What is the difference between value and defaultValue?

Answer: value controls the current value of an input through React. defaultValue specifies the initial value while leaving subsequent changes to the DOM.

Q4. What is useRef()?

Answer: useRef() is a React Hook that returns a persistent object with a current property. It can reference a DOM element or store a value that does not need to trigger a re-render when changed.

Q5. Do uncontrolled components need onChange handlers?

Answer: Not merely to maintain the current input value. The browser updates the DOM value. However, an event handler can still be useful for logging, validation, or other behavior.

Q6. Are uncontrolled components faster than controlled components?

Answer: Not always. Uncontrolled inputs avoid updating React state for every keystroke, but actual performance depends on the component tree, event handling, and application requirements.

Q7. Can a textarea be uncontrolled?

Answer: Yes. A textarea can use defaultValue for its initial text, and its current value can be read through a ref or form data.

Q8. How do you make an uncontrolled checkbox initially selected?

Answer: Use defaultChecked={true}. The browser then manages the checkbox's selected state as the user interacts with it.

Q9. Why are file inputs commonly uncontrolled?

Answer: Browsers restrict programmatic setting of a file input's selected file value. Applications normally read the selected files through the DOM's files property.

Q10. Can uncontrolled components use React state?

Answer: Yes. React state can store submission results or other UI data. The term uncontrolled describes how the input's current value is managed, not whether the entire component is forbidden from using state.

Q11. What does event.preventDefault() do in a form submit handler?

Answer: It prevents the browser's default submission action, allowing the React handler to process the form without the usual page navigation or reload.

Q12. When should you prefer controlled components?

Answer: Prefer controlled components when input values must drive immediate rendering, real-time validation, conditional UI, live filtering, or coordinated behavior across multiple fields.


18. Practice Exercises

  1. Create an uncontrolled input that displays the entered name when a button is clicked.
  2. Build a login form with username and password fields using refs.
  3. Create a feedback form with a textarea and read the message on submit.
  4. Build a course-selection form with an uncontrolled select element and defaultValue.
  5. Create a checkbox form and read the checked state on submission.
  6. Build a file input that displays the selected file's name and size.
  7. Create a student registration form with name, email, and course fields.
  8. Modify the registration form to collect values with FormData instead of using a separate ref for each input.
  9. Compare a controlled input and an uncontrolled input by building both versions of the same form.
  10. Add appropriate labels, required fields, and browser validation to a contact form.

19. Quick Revision

  • An uncontrolled component keeps its current form value in the DOM.
  • useRef() can provide access to the DOM element.
  • ref.current.value reads the current value of a text input.
  • defaultValue sets an initial text, textarea, or select value.
  • defaultChecked sets an initial checkbox or radio selection.
  • FormData can collect values from named form controls.
  • File inputs are commonly handled as uncontrolled elements.
  • Use event.preventDefault() when handling form submission without normal browser navigation.
  • Changing a ref does not trigger a React re-render.
  • Use controlled inputs when React must respond to every input change.

20. Official React Documentation


21. React JS Training at JustAcademy

Strengthen your React JS fundamentals by practising components, JSX, props, state, forms, refs, event handling, and real-world projects.

JustAcademy React JS Training

Interested in learning more or exploring a course demo? Use the link below.

Register for React JS Course Demo


Conclusion

Uncontrolled components are useful when the browser can manage form values and React only needs to read them at specific times. By using useRef(), defaultValue, defaultChecked, and the FormData API, you can build simple and effective forms without storing every keystroke in React state. For interfaces that require immediate validation or dynamic updates based on input, controlled components are often the better option.

Previous Next
whatsapp