React useState
useState is the hook you'll use most. It adds a state variable to a component: a value React remembers between renders, and that triggers a re-render whenever you change it.
const [value, setValue] = useState(initialValue);useState returns an array with exactly two items, which we destructure:
| Item | Meaning |
|---|---|
value |
the current state for this render |
setValue |
function to request a new value and re-render |
initialValue |
used only on the first render |
A basic example
import { useState } from 'react';
export default function App() {
const [color, setColor] = useState('tomato');
return (
<div>
<div style={{ width: 120, height: 120, background: color, borderRadius: 12, transition: 'background .3s' }} />
<p>Current colour: {color}</p>
{['tomato', 'gold', 'mediumseagreen', 'royalblue'].map((c) => (
<button key={c} onClick={() => setColor(c)} style={{ marginRight: 4 }}>{c}</button>
))}
</div>
);
}State is a snapshot
Inside one render, a state variable is a constant. Calling the setter doesn't change the variable you already have — it schedules a new render where the variable will have the new value:
import { useState } from 'react';
export default function App() {
const [count, setCount] = useState(0);
function addThree() {
setCount(count + 1);
setCount(count + 1);
setCount(count + 1);
console.log('count inside handler is still', count);
}
function reallyAddThree() {
setCount((c) => c + 1);
setCount((c) => c + 1);
setCount((c) => c + 1);
}
return (
<div>
<p style={{ fontSize: 28 }}>{count}</p>
<button onClick={addThree}>+3 (broken: adds 1)</button>{' '}
<button onClick={reallyAddThree}>+3 (updater functions)</button>
</div>
);
}The first button calls setCount(0 + 1) three times, because count is 0 throughout the handler. The second button passes updater functions: React queues them and feeds each the result of the previous one.
Tip: Use the updater form
setX(prev => …)whenever the new value depends on the old one, especially inside timers or async code.
Objects in state
State can hold any value. When it holds an object, replace it with a new object — never mutate it — and copy the fields you keep with spread:
import { useState } from 'react';
export default function App() {
const [profile, setProfile] = useState({ name: 'Duc', city: 'Da Lat', settings: { darkMode: false } });
return (
<div style={{ background: profile.settings.darkMode ? '#222' : '#fff', color: profile.settings.darkMode ? '#eee' : '#222', padding: 12, width: 300 }}>
<input value={profile.name} onChange={(e) => setProfile({ ...profile, name: e.target.value })} />
<input value={profile.city} onChange={(e) => setProfile({ ...profile, city: e.target.value })} />
<label style={{ display: 'block', marginTop: 6 }}>
<input
type="checkbox"
checked={profile.settings.darkMode}
onChange={(e) => setProfile({ ...profile, settings: { ...profile.settings, darkMode: e.target.checked } })}
/>{' '}
Dark mode
</label>
<p>{profile.name} from {profile.city}</p>
</div>
);
}Why not profile.name = 'X'; setProfile(profile)? React compares the old and new values with Object.is. The same object reference looks "unchanged", so React may skip the re-render.
Arrays in state
| Goal | Mutating ❌ | Non-mutating ✅ |
|---|---|---|
| add | push, unshift |
[...arr, item], [item, ...arr] |
| remove | splice, pop |
arr.filter(x => x.id !== id) |
| replace | arr[i] = x |
arr.map(x => x.id === id ? newX : x) |
| sort | sort, reverse |
arr.toSorted(), [...arr].reverse() |
import { useState } from 'react';
export default function App() {
const [tags, setTags] = useState(['react', 'hooks']);
const [draft, setDraft] = useState('');
function addTag(e) {
e.preventDefault();
const tag = draft.trim().toLowerCase();
if (tag && !tags.includes(tag)) setTags([...tags, tag]);
setDraft('');
}
return (
<form onSubmit={addTag}>
<input value={draft} onChange={(e) => setDraft(e.target.value)} placeholder="Add a tag and press Enter" />
<div style={{ marginTop: 8 }}>
{tags.map((t) => (
<span key={t} style={{ background: '#e0f2fe', padding: '2px 8px', borderRadius: 12, marginRight: 6 }}>
#{t} <button type="button" onClick={() => setTags(tags.filter((x) => x !== t))} style={{ border: 'none', background: 'none' }}>✕</button>
</span>
))}
</div>
<button type="button" onClick={() => setTags(tags.toSorted())} style={{ marginTop: 8 }}>Sort A–Z</button>
</form>
);
}Lazy initial state
If the initial value is expensive to compute (for example reading localStorage), pass a function. React calls it only on the first render:
const [notes, setNotes] = useState(() => JSON.parse(localStorage.getItem('notes') ?? '[]'));Writing useState(JSON.parse(...)) instead would parse on every render and then throw the result away.
How many state variables?
- Use separate
useStatecalls for unrelated values (name,isOpen). - Group values that always change together into one object (
{ x, y }of a position). - Don't store what you can compute: if you have
items, don't also storeitemCount. - For many related updates, consider
useReducer.
Test yourself
count is 5. A handler calls setCount(count + 1) twice. What is count on the next render?
- 5
- 6
- 7
- It depends on timing
Which correctly updates user.email in state?
- user.email = e; setUser(user)
- setUser({ ...user, email: e })
- setUser.email(e)
- useState({ email: e })
When is the initial value passed to useState used?
- On every render
- Only on the first render
- Whenever the setter is called
- When the component unmounts