React Forms

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 2 min

React Forms

Handling forms is a critical part of almost any web application. In traditional HTML, form elements like <input>, <textarea>, and <select> typically maintain their own state and update it based on user input.

In React, the way we handle forms is slightly different because React prefers to be the “single source of truth” for all data in the UI.

The Two Approaches to Forms in React

When building forms in React, you have to choose between two primary architectures:

  1. Controlled Components: React manages the state of the form. Every keystroke updates a React state variable, and the input field is forced to display whatever value is in that state variable. This is the recommended and most common approach.
  2. Uncontrolled Components: The DOM manages the state of the form (just like traditional HTML). React only interacts with the form when it needs to (usually when the form is submitted) by reading the values using a ref.

The Basic Form Submission

Regardless of whether you use controlled or uncontrolled components, you should always handle the submission of the form using the onSubmit event handler on the <form> element itself, rather than an onClick handler on the submit button.

This ensures that the form can be submitted by pressing the “Enter” key, which is important for accessibility and user experience.

You must also call event.preventDefault() to stop the browser’s default behavior, which is to refresh the entire page.

function BasicForm() {
  const handleSubmit = (event) => {
    // 1. Stop the browser from refreshing the page
    event.preventDefault();
    
    // 2. Process the form data...
    console.log("Form submitted!");
  };

  return (
    <form onSubmit={handleSubmit}>
      <input type="text" name="username" />
      
      {/* 
        This button will trigger the form's onSubmit event 
        because it is inside the <form> tags. 
      */}
      <button type="submit">Submit</button>
    </form>
  );
}

Form Libraries

While you can build complex forms using standard React state, it quickly becomes tedious to manually manage validation, error messages, and touched states for dozens of inputs.

For complex applications, the React community relies heavily on third-party form libraries. The most popular modern choice is React Hook Form, followed by Formik.

These libraries abstract away the boilerplate and provide highly performant, uncontrolled (or controlled) form management out of the box.

Interview Questions

Q: How do you prevent the browser from reloading the page when a React form is submitted?
A: Native HTML forms trigger a full page refresh on submit. You must explicitly call e.preventDefault() inside your onSubmit handler attached to the <form>.