useState is a built-in React Hook that lets a component remember information between renders. It is the most commonly used Hook in React and is usually the first one developers learn.
Overview
A React component is just a function, and a normal function forgets its variables every time it runs. When something on screen needs to change, like a counter, a typed input, or an open or closed menu, the component needs a way to keep that value and re-draw itself when it changes. useState does both.
Syntax
const [count, setCount] = useState(0);
This line gives you two things:
-
State value (
count): the current stored value. -
Setter function (
setCount): the only proper way to change that value.
The number inside useState(0) is the initial value, used only on the first render.
How it works
- The component renders for the first time and
countis0. - The user does something, like clicking a button.
- The code calls
setCount(1). - React saves the new value and re-renders the component.
- The component runs again, and this time
countis1.
The key idea is that changing state tells React to update the screen. Changing a normal variable does not.
Basic example
function Counter() {
const [count, setCount] = useState(0);
return <button onClick={() => setCount(count + 1)}>{count}</button>;
}
Each click raises the number by one.
What can be stored
State can hold any type of value:
- Numbers and text
- True or false values
- Arrays (like a to-do list)
- Objects (like form data)
Rules and common mistakes
-
Never change state directly. Writing
count = 5does nothing visible. Always use the setter. -
Don't mutate arrays or objects. Make a new copy and pass that to the setter, for example
setItems([...items, newItem]). - Updates are not instant. After calling the setter, the variable keeps its old value until the next render.
-
Use the function form when the new value depends on the old one:
setCount(prev => prev + 1). This is safer when several updates happen quickly. - Call Hooks only at the top level of a component, never inside loops, conditions, or nested functions.
When to use it
Use useState for simple, local data that belongs to one component, such as input text, toggles, and counters. If many components need the same data, consider lifting the state up to a parent or using Context. For complex state with many related updates, useReducer may be a better fit.
Quick summary
| Term | Meaning |
|---|---|
| State | Data a component remembers |
| Setter | Function that updates the state |
| Re-render | React redrawing the component with new state |
| Initial value | Starting value, used once |
Top comments (0)