Home / Learn React / State with useState
State with useState
State is a component's memory. When state changes, React runs the component again and the screen updates. The hook for it is useState.
Theory in plain words
What it is
State is data that belongs to one component and can change over time: a counter, the text in an input, whether a menu is open. useState returns the current value and a function to change it.
Why we use it
A normal variable is reset every time the component function runs, and changing it does not update the screen. State is kept by React between renders and changing it tells React to render again.
How it works
React stores the state outside your function, in a slot for that component. On every render it hands you the current value. Calling setX(new) schedules a render. During that render useState returns the new value.
Where it is used
- Counters, likes, toggles, tabs
- Form fields and filters
- Open or closed menus, modals and accordions
- Data you loaded from a server
A counter
In a real project write import { useState } from "react" and use useState(0).
Why not a normal variable?
The variable changes (see the console) but the screen does not, and it resets on the next render.
Many states, each independent
Each component copy has its own state
Clicking A does not change B. State belongs to one place in the tree.
count = count + 1 does nothing. Always call the setter. Also do not call hooks inside loops, conditions or nested functions.Quick quiz
1. What does useState return?
const [value, setValue] = useState(initial).
2. Why does changing a normal variable not update the screen?
Only state changes trigger a render and state survives renders.
3. Do two copies of a component share state?
State belongs to a component instance position in the tree.
Common questions
What does useState return?
An array: the current value and a setter. const [value, setValue] = useState(initial).
Why does changing a normal variable not update the screen?
React is not told to render again, and the variable resets. Only state changes trigger a render and state survives renders.
Do two copies of a component share state?
No, each copy has its own state. State belongs to a component instance position in the tree.