State & Core HooksCore· 40 min read

Forms & Controlled Inputs

Connect form inputs to state so React always knows their values — the “controlled component” pattern.

What you will learn

  • Build controlled inputs with state
  • Handle form submission
  • Read all form values

Controlled inputs

A controlled input ties an input’s value to state and updates state onChange. React becomes the single source of truth for the value.

A controlled form input
function App() {
  const [email, setEmail] = useState("");

  function handleSubmit(e) {
    e.preventDefault();
    alert("Submitting: " + email);
  }

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
        placeholder="Your email"
      />
      <button type="submit">Sign up</button>
      <p>Preview: {email}</p>
    </form>
  );
}
Live preview

Here is the whole round-trip of a controlled form, step by step:

  1. State holds the value: const [email, setEmail] = useState("") starts the email empty.
  2. The input shows the state: value={email} — the box always displays what is in state.
  3. Typing updates the state: onChange={(e) => setEmail(e.target.value)} runs on every keystroke and saves the new text.
  4. React re-renders, so the live preview {email} under the form updates instantly.
  5. On submit, handleSubmit runs. e.preventDefault() stops the browser from reloading the page, then we use the value (here, an alert).

Note: Output: An email box, a Sign up button, and a live Preview: line. Type in the box and the preview updates as you type. Click Sign up and an alert reads “Submitting: ” followed by what you typed.

Tip: The pattern is always the same: value={state} + onChange={e => setState(e.target.value)}. Once you know it for one input, you know it for all of them.

Note: Remember e.preventDefault() in the submit handler to stop the page reloading — just like in the JavaScript forms lesson.

Q. What makes an input “controlled” in React?

Answer: A controlled input’s value comes from state and is updated via onChange, making React the single source of truth.

✍️ Practice

  1. Build a controlled text input and show its value live below it.
  2. Build a form with two fields that alerts both values on submit.

🏠 Homework

  1. Build a contact form (name, email, message) as controlled inputs that logs all values on submit.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →