ReactEasy

Can we use multiple state variables?

Yes. Call useState as many times as you need; each call creates an independent state variable. React keeps them apart by call order, so every render must call the hooks in the same order.

Separate variables vs one object

  • Separate useState calls: best for unrelated values (isOpen, query, page). Updates are simple and independent.
  • One object: best for values that always change together ({ x, y } position, form fields submitted as a whole). Remember the setter replaces; spread to keep other fields.
  • useReducer: best when updates involve several fields and rules (state machines, multi-step forms).

Guidelines from the React docs

  • Group related state that changes together.
  • Avoid contradictions: instead of isSending and isSent booleans that can both be true, use one status: "idle" | "sending" | "sent".
  • Avoid redundant state: do not store fullName if you have firstName and lastName.
  • Avoid duplication: store the selected item's ID, not a copy of the item.
  • Avoid deep nesting: flatten (normalize) state where possible.

Batching

Multiple setters called in the same event are batched into one render, so splitting state does not cause extra renders.

Code example

tsx
1import { useState } from "react";
2
3type Status = "idle" | "sending" | "sent" | "error";
4
5export function ContactForm() {
6 // Unrelated values: separate state variables
7 const [isOpen, setIsOpen] = useState(false);
8 const [status, setStatus] = useState<Status>("idle"); // one status, not two booleans
9
10 // Values that change together: one object
11 const [form, setForm] = useState({ name: "", email: "", message: "" });
12
13 const update = (field: keyof typeof form) => (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) =>
14 setForm((f) => ({ ...f, [field]: e.target.value }));
15
16 async function send() {
17 setStatus("sending");
18 try {
19 await fetch("/api/contact", { method: "POST", body: JSON.stringify(form) });
20 setStatus("sent");
21 setIsOpen(false); // both updates batched into one render
22 } catch {
23 setStatus("error");
24 }
25 }
26
27 if (!isOpen) return <button onClick={() => setIsOpen(true)}>Contact us</button>;
28 return (
29 <div>
30 <input value={form.name} onChange={update("name")} placeholder="Name" />
31 <input value={form.email} onChange={update("email")} placeholder="Email" />
32 <textarea value={form.message} onChange={update("message")} />
33 <button disabled={status === "sending"} onClick={send}>Send</button>
34 {status === "error" && <p role="alert">Failed, try again</p>}
35 </div>
36 );
37}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app