The useState call
- React course
- Beginner
- Lesson 41/84
- 4 min
Learn that useState returns a value and a setter.
Calling useState
You call useState at the top of the component, unconditionally. Calling it inside loops, conditions or nested functions is forbidden; React remembers by call order.
If you have several pieces of state you make several useState calls, one per line. The order must stay the same on every render.
This rule is called the "rules of hooks"; we cover it in detail later.
Initial value
The first argument to useState is the initial value. It can be a number, string, array, object or null.
The initial value is used only on the first render. Later renders return the remembered value; the initial is not recomputed.
If the initial value is an expensive computation, you can pass it as a function: useState(() => compute()). We cover this later.
Practice Name state
Complete the skeleton. Write a NameTag component; import useState. Define const [name, setName] = useState("Alex"); and return <p>Hello {name}</p>. Export it.
Starter code
import { useState } from "react";
// Define NameTag hereSample solution
import { useState } from "react";
function NameTag() {
const [name, setName] = useState("Alex");
return <p>Hello {name}</p>;
}
export default NameTag;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 The useState call: fill in the missing part
const [name, setName] = useState(____);
const [name, setName] = useState("Alex");
Explanation: The initial value is a string.
2 Where is it forbidden to call useState?
Hooks must be called in the same order every render.- At the top of the component
- Before another hook
- In the component body
- Inside an if block Correct answer
Explanation: Calling inside a condition breaks the rules of hooks.
3 The useState call: match the terms
| Term | Meaning |
|---|---|
useState(0) |
Number start |
useState("") |
Empty string |
useState([]) |
Empty array |
useState(null) |
Null start |