🎓 A1Learner
🔍
0 of 50 lessons completed

Form State in One Object

Form state in one object keeps every field in a single state value. One useState call holds the whole form.

One object, two fields

The paragraph reads both keys from the form object.

const [form, setForm] = useState({ name: 'Ada', city: 'Paris' });
return <p>{form.name} from {form.city}.</p>;

Update one key

Three dots copy the form and change only the name.

const [form, setForm] = useState({ name: 'Ada', city: 'Paris' });
const next = { ...form, name: 'Mia' };
return <p>{next.name} from {next.city}.</p>;

Example

import { useState } from 'react';

export default function App() {
  const [form, setForm] = useState({ name: '', city: '' });

  function handleChange(e) {
    setForm({ ...form, [e.target.name]: e.target.value });
  }

  return (
    <div>
      <input name="name" value={form.name} onChange={handleChange} />
      <input name="city" value={form.city} onChange={handleChange} />
      <p>{form.name} from {form.city}.</p>
    </div>
  );
}

Key points

  • The state value is an object with one key per field.
  • Each input reads its own key from the object.
  • Three dots copy the object before one key changes.
  • The handler uses the input name to pick the key.
  • One handler can update every field in the form.

In this example, the form state value holds name and city. Each input reads its own key from form. The name attribute tells the handler which key to change. The handler copies form with three dots and sets the named key. The paragraph shows both keys.

Note

Copy first, so the other fields keep their values.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

How does one handler update one key in a form state object?