Frontend School
DashboardProblemsLearnPracticeMock InterviewReportsStatsBuy Credits
DashboardProblemsLearnPracticeMock Interview
React Fundamentals
  1. 1.Introduction to React & Development Environment
  2. 2.JSX, Components & Props
  3. 3.Managing Component State with useState
  4. 4.Event Handling & Conditional Rendering
  5. 5.Rendering Lists & Basic useEffect
  6. 6.Deep Dive into useEffect Hook
  7. 7.useRef and useReducer for Complex State
  8. 8.Optimizing Performance with useMemo & useCallback
  9. 9.Context API & Custom Hooks for Reusability
  10. 10.Client-Side Routing with React Router
  11. 11.Forms, Validation & Data Fetching Patterns
  12. 12.Advanced Performance Optimization & Reconciliation
  13. 13.State Management Libraries (Redux Toolkit & Alternatives)
  14. 14.Testing React Components with Jest & React Testing Library
  15. 15.Advanced React Features & Modern Concepts
React Fundamentals
11

React · Lesson 11 of 15 · 4 min

Forms, Validation & Data Fetching Patterns

This is where you prove you can handle user input from the browser to the backend, a core skill for any frontend role.

After this lesson, you'll be able to whiteboard a complete form component, explain the trade-offs between different state management patterns, and articulate a robust data submission strategy. This topic is not about obscure trivia; it's about demonstrating you can build reliable user interfaces.

Choosing Between Controlled and Uncontrolled Inputs

Every form starts with a fundamental choice for each input: does React control its value, or does the DOM?

Controlled components are the default in React. The input's value is driven by component state, and any change to the input updates that state via an onChange handler. React is the single source of truth.

Use this pattern for almost everything. It makes implementing instant validation, conditional logic (disabling a button if a field is empty), or dynamic input formatting straightforward.

Uncontrolled components let the DOM handle the input's state. You read the value when you need it, typically on form submission, using a ref.

Reserve this for specific cases:

  1. File inputs: The <input type="file" /> value is read-only and can only be handled this way.
  2. Integrating with non-React code: When using a jQuery plugin or another library that directly manipulates the DOM.
  3. Avoiding re-renders on every keystroke: A potential micro-optimization for complex forms with hundreds of inputs, but premature optimization is a bigger risk. Stick to controlled unless you have measured a performance problem.

The trap: Candidates often mix the two. If you pass a value prop to an input but no onChange handler, React will make the input read-only. This is a common "gotcha." You must either control the input completely or not at all (by using defaultValue or no value prop).

Implementing Client-Side Validation

Client-side validation is for user experience, not security. It provides immediate feedback and prevents a user from submitting a form with obvious errors. Never trust it as your only line of defense.

A common and effective pattern is to maintain two state objects: one for the form data and one for the validation errors.

const [formData, setFormData] = useState({ email: '', password: '' });
const [errors, setErrors] = useState({ email: '', password: '' });

On submit, you run a validate function that checks the formData and populates the errors object. If the errors object is empty, the submission proceeds. Otherwise, you use the errors object to render error messages next to the corresponding fields.

For anything beyond a few simple fields, a manual validate function becomes boilerplate. Mentioning schema-based libraries like Zod or Yup shows you know how to scale this pattern. They let you declare validation rules declaratively, keeping your component logic clean.

Here is a standard implementation of a controlled form with manual validation. Notice how the formData and errors states work together.

import React, { useState } from 'react';

function RegistrationForm() {
  const [formData, setFormData] = useState({
    email: '',
    password: '',
    confirmPassword: '',
  });
  const [errors, setErrors] = useState({
    email: '',
    password: '',
    confirmPassword: '',
  });

  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = event.target;
    setFormData((prev) => ({ ...prev, [name]: value }));
  };

  const validate = () => {
    const newErrors = { email: '', password: '', confirmPassword: '' };
    let isValid = true;

    if (!formData.email) {
      isValid = false;
      newErrors.email = 'Email is required';
    } else if (!/\S+@\S+\.\S+/.test(formData.email)) {
      isValid = false;
      newErrors.email = 'Email is invalid';
    }

    if (formData.password.length < 8) {
      isValid = false;
      newErrors.password = 'Password must be at least 8 characters';
    }

    if (formData.password !== formData.confirmPassword) {
      isValid = false;
      newErrors.confirmPassword = 'Passwords do not match';
    }

    setErrors(newErrors);
    return isValid;
  };

  const handleSubmit = (event: React.FormEvent<HTMLFormEvent>) => {
    event.preventDefault();
    if (validate()) {
      console.log('Form is valid. Submitting:', formData);
      // API call would go here
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label htmlFor="email">Email</label>
        <input
          type="email"
          id="email"
          name="email"
          value={formData.email}
          onChange={handleChange}
        />
        {errors.email && <p style={{ color: 'red' }}>{errors.email}</p>}
      </div>
      {/* ... other fields for password and confirmPassword ... */}
      <button type="submit">Register</button>
    </form>
  );
}

Managing the Form Submission Lifecycle

A form submission is an asynchronous state machine. Your component must manage the transitions between idle, loading, success, and error states. Failing to do so creates a poor and confusing user experience.

The flow begins in your onSubmit handler. The first line must always be event.preventDefault(). Forgetting this causes a full-page reload, which is an immediate red flag in an interview.

After preventing the default behavior and running client-side validation, you transition to the loading state.

const [isSubmitting, setIsSubmitting] = useState(false);
const [submitError, setSubmitError] = useState<string | null>(null);

const handleSubmit = async (event: React.FormEvent) => {
  event.preventDefault();
  if (!validate()) return;

  setIsSubmitting(true);
  setSubmitError(null);

  try {
    await api.submitForm(formData);
    // Handle success: show message, redirect, clear form
  } catch (error) {
    setSubmitError('An error occurred. Please try again.');
  } finally {
    setIsSubmitting(false);
  }
};

These state flags drive the UI. While isSubmitting is true, disable the submit button and show a spinner. If submitError is not null, display it. This prevents double submissions and clearly communicates the application's status to the user.

This diagram shows the complete flow, which you should be able to describe.

The interview question: "How do you prevent a user from submitting a form multiple times?" The answer is to use a loading state. Once submission starts, set a state variable like isSubmitting to true and use it to apply the disabled attribute to the submit button. Set it back to false in a finally block to ensure the button is re-enabled even if the API call fails.

Try it

In a local React project, build a simple login form with an email and a password field. Implement controlled components for both. On submit, run a validation check that ensures the password is at least 8 characters long. If valid, simulate a 2-second API call using setTimeout inside a Promise. While the "API call" is running, the submit button should be disabled and its text should change to "Logging in...".

Next: We'll look at techniques for optimizing your component's render performance in "Advanced Performance Optimization & Reconciliation".

Lock it in — apply this lesson under interview conditions.

Try an AI mock interview
Previous

Client-Side Routing with React Router

Next

Advanced Performance Optimization & Reconciliation