# Form State Management

> How to handle form inputs in React using controlled components, where React state acts as the single source of truth.

Subject: React | Lesson 38 of 48 | 6 min read
Interactive lesson: https://codewithanimation.in/react/form-state-management
Previous: [React Router DOM](https://codewithanimation.in/react/react-router-dom.md) | Next: [Controlled Inputs & Validation](https://codewithanimation.in/react/controlled-inputs-validation.md)

## The 'Controlled Component' Pattern

In standard HTML, form elements like `<input>`, `<textarea>`, and `<select>` maintain their own internal state based on user input.

In React, we typically prefer to keep all changing data in React's state. When we bind an input's `value` to a state variable and update that variable on `onChange`, we create a **Controlled Component**.

In a controlled component, the React state is the "single source of truth". The input only displays what the state tells it to display.

## Why control inputs?

Controlling inputs gives you absolute power over the data.

Because you have the exact string the user typed in a state variable on every keystroke, you can easily:

1. Force input formatting (e.g., uppercase only, or phone number masking).

2. Disable the submit button if the input is invalid.

3. Show real-time validation errors as the user types.

4. Pass the current input value to other components (like a live preview).

## Handling Multiple Inputs

If you have a form with one input, a single `const [email, setEmail] = useState('')` is fine. But for forms with many fields, this gets tedious.

Instead, you can use a single state object to hold all form fields:

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

Then, use a single `onChange` handler that reads the `name` attribute from the input to update the correct property dynamically:

`setFormData({ ...formData, [e.target.name]: e.target.value });`

## Common mistake: The Re-render Cost

The downside of controlled components is that every single keystroke triggers a state update, causing the component (and all its children) to re-render.

For small forms, this is completely fine. But for massive forms or tables, this can cause significant typing lag. In those extreme cases, uncontrolled components (using `useRef`) or specialized libraries (like React Hook Form) are preferred.

## Tip: Prevent Default Behavior

When a user clicks the submit button inside a `<form>`, the browser will try to send an HTTP request and refresh the page. You must always call `e.preventDefault()` inside your `onSubmit` handler to stop this and handle the submission via JavaScript.

## Try it: The Source of Truth

Type into the login form below. Notice how the React State object (the single source of truth) updates instantly on every keystroke, driving the UI.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/react/form-state-management

## Check yourself

### Question 1

What makes an `<input>` component 'controlled' in React?

- A. It is wrapped in a `<form>` element.
- B. Its `value` is tied directly to a React state variable, and it updates that state via `onChange`.
- C. Its value is read using a `useRef` hook when the form is submitted.

Correct answer: B

A controlled component derives its value entirely from React state, making React the single source of truth.

### Question 2

If you use an object for form state like `const [form, setForm] = useState({ age: 0, name: '' })`, how do you safely update just the `name`?

- A. `setForm({ name: e.target.value })`
- B. `form.name = e.target.value`
- C. `setForm({ ...form, name: e.target.value })`

Correct answer: C

You must spread the existing state object (`...form`) to copy over the unchanged properties before overwriting the `name` property.

- Why not A: This would delete the `age` property.
- Why not B: Never mutate state directly.

### Question 3

What is the first thing you should do in a form's `onSubmit` handler?

- A. `e.preventDefault();`
- B. `setFormData({});`
- C. `console.log(e.target.value);`

Correct answer: A

If you do not call `e.preventDefault()`, the browser will submit the form natively, which will reload the page and destroy your React app's state.

## Remember this

- Controlled components use React state as the single source of truth.
- Bind the `value` prop to state, and update it in `onChange`.
- For complex forms, use an object in state and the input's `name` attribute to update dynamically.
- Always call `e.preventDefault()` on form submission to prevent page reloads.
- Be aware that typing in a controlled input triggers a re-render on every keystroke.
