codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
⚛️

React.js

16 / 61 topics
10Lifecycle Methods Overview11ComponentDidMount Lifecycle Method12ComponentDidUpdate Lifecycle Method13ComponentWillUnmount Lifecycle Method14Conditional Rendering in React15Rendering Lists and Using Keys16Handling Forms in React17Lifting State Up
Tutorials/React.js/Handling Forms in React
⚛️React.js

Handling Forms in React

Updated 2026-04-20
3 min read

Introduction

Forms are a fundamental part of web applications, allowing users to input data and interact with your application. In React, handling forms can be done using controlled components or uncontrolled components. This tutorial will cover both methods, along with best practices and real-world examples.

Controlled Components

Controlled components in React are form elements whose values are controlled by the state of the component. The value of the input element is set by the value attribute, and any changes to the input are handled through event handlers like onChange.

Basic Example

Let's start with a simple example of a controlled input field.

import React, { useState } from 'react';

function NameForm() {
  const [name, setName] = useState('');

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

  const handleSubmit = (event) => {
    event.preventDefault();
    alert('A name was submitted: ' + name);
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Name:
        <input type="text" value={name} onChange={handleChange} />
      </label>
      <input type="submit" value="Submit" />
    </form>
  );
}

export default NameForm;

Explanation

  1. State Initialization: We use the useState hook to create a state variable name and a function setName to update it.
  2. Event Handling: The handleChange function updates the state whenever the input changes, making the component "controlled".
  3. Form Submission: The handleSubmit function prevents the default form submission behavior and alerts the user with the submitted name.

Benefits of Controlled Components

  • Predictable State: The state is the single source of truth.
  • Easy Validation: You can easily validate input as it changes.
  • Reproducible Behavior: Forms behave consistently across different renders.

Uncontrolled Components

Uncontrolled components store their own state in the DOM. To access the value, you use a ref to get the value from the DOM element.

Basic Example

Here's how you can implement an uncontrolled component for a form.

import React, { useRef } from 'react';

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

  const handleSubmit = (event) => {
    event.preventDefault();
    alert('A name was submitted: ' + inputRef.current.value);
  };

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

export default NameForm;

Explanation

  1. Ref Initialization: We use the useRef hook to create a reference to the input element.
  2. Accessing DOM Value: In the handleSubmit function, we access the input's value using inputRef.current.value.

Benefits of Uncontrolled Components

  • Simplicity: Less code and easier to implement for simple forms.
  • Performance: Can be more performant for large forms as it doesn't require re-rendering on every change.

Handling Multiple Inputs

For forms with multiple inputs, you can use a single state object to manage all the input values.

Example

import React, { useState } from 'react';

function Reservation() {
  const [formData, setFormData] = useState({
    firstName: '',
    lastName: '',
    isGoing: true,
    numberOfGuests: 2,
  });

  const handleChange = (event) => {
    const { name, value, type, checked } = event.target;
    setFormData({
      ...formData,
      [name]: type === 'checkbox' ? checked : value,
    });
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    alert('A reservation was submitted for: ' + formData.firstName);
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        First Name:
        <input
          name="firstName"
          type="text"
          value={formData.firstName}
          onChange={handleChange}
        />
      </label>
      <br />
      <label>
        Last Name:
        <input
          name="lastName"
          type="text"
          value={formData.lastName}
          onChange={handleChange}
        />
      </label>
      <br />
      <label>
        Is going:
        <input
          name="isGoing"
          type="checkbox"
          checked={formData.isGoing}
          onChange={handleChange}
        />
      </label>
      <br />
      <label>
        Number of guests:
        <input
          name="numberOfGuests"
          type="number"
          value={formData.numberOfGuests}
          onChange={handleChange}
        />
      </label>
      <br />
      <button type="submit">Submit</button>
    </form>
  );
}

export default Reservation;

Explanation

  1. State Initialization: We use a single state object formData to manage all input values.
  2. Dynamic Handling: The handleChange function updates the state based on the input's name attribute, making it reusable for multiple inputs.

Best Practices

  • Use Controlled Components for Complex Forms: They provide better control and validation capabilities.
  • Avoid Inline Functions in Render: Define event handlers outside the render method to avoid unnecessary re-renders.
  • Validate Input: Use libraries like Formik or React Hook Form for complex validation needs.
  • Accessibility: Ensure forms are accessible by using appropriate HTML attributes and ARIA roles.

Conclusion

Handling forms in React is a crucial skill for building interactive web applications. Whether you choose controlled or uncontrolled components, understanding the underlying concepts will help you build robust and maintainable forms. By following best practices and leveraging React's powerful features, you can create seamless user experiences.


PreviousRendering Lists and Using KeysNext Lifting State Up

Recommended Gear

Rendering Lists and Using KeysLifting State Up