Multiple state values
- React course
- Beginner
- Lesson 43/84
- 4 min
Learn to use several useState calls in one component.
Multiple pieces of state
A component can have several pieces of state. You make a separate useState call for each: const [name, setName] = useState("") and const [age, setAge] = useState(0).
You can also group related values into one object: const [form, setForm] = useState({name: "", age: 0}). Then you update with spread: setForm(f => ({...f, name: "Alex"})).
Both approaches are fine; choose based on how related the values are.
Updating object state
When updating object state, direct mutation: form.name = "Alex" is wrong. React does not see it.
The right way is to produce a new object with spread: setForm(f => ({...f, name: "Alex"})). It keeps the old fields and changes only name.
Later we will see useReducer for tidier object updates; for now spread is enough.
Practice Two pieces of state
Complete the skeleton. Write a Profile component; import useState. Define const [name, setName] = useState("Alex"); and const [age, setAge] = useState(30);. Return <p>{name} - {age}</p>. Export it.
Starter code
import { useState } from "react";
// Define Profile hereSample solution
import { useState } from "react";
function Profile() {
const [name, setName] = useState("Alex");
const [age, setAge] = useState(30);
return <p>{name} - {age}</p>;
}
export default Profile;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Multiple state values: match the terms
| Term | Meaning |
|---|---|
name |
Name state |
age |
Age state |
form |
Object state |
spread ...f |
Object update |
2 What is the clean way to hold related name and age?
Object state updates with spread.- Two separate useState
- A single object useState Correct answer
- A prop
- A global variable
Explanation: Grouping related values in one object makes updates easier.
3 Multiple state values: fill in the missing part
setForm(f => ({ ...f, name: ____ }))
setForm(f => ({ ...f, name: "Alex" }))
Explanation: You updated the name field.