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
useStatecalls: 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
isSendingandisSentbooleans that can both be true, use onestatus: "idle" | "sending" | "sent". - Avoid redundant state: do not store
fullNameif you havefirstNameandlastName. - 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";23type Status = "idle" | "sending" | "sent" | "error";45export function ContactForm() {6 // Unrelated values: separate state variables7 const [isOpen, setIsOpen] = useState(false);8 const [status, setStatus] = useState<Status>("idle"); // one status, not two booleans910 // Values that change together: one object11 const [form, setForm] = useState({ name: "", email: "", message: "" });1213 const update = (field: keyof typeof form) => (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) =>14 setForm((f) => ({ ...f, [field]: e.target.value }));1516 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 render22 } catch {23 setStatus("error");24 }25 }2627 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.