State with useState
Add interactivity — useState hook, re-renders, and state update patterns
Free tier: read the explanation here. Upgrade to Pro for Drills, Speed challenges & Mastery badges.
UpgradeKnowledge Debt detected
You can study this freely — but your score may plateau if these foundations have gaps. The Mastery badge requires them to be solid.
Explanation
is data that can change over time. When state changes, React the component.
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0); // initial value = 0
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>+</button>
<button onClick={() => setCount(count - 1)}>-</button>
</div>
);
}useState returns [currentValue, setterFunction].
Rules of Hooks:
- 1. Only call hooks at the top level (never inside loops, conditions, or nested functions)
- 2. Only call hooks in React function components (or custom hooks)
Functional updates — use when new state depends on old state: ``jsx setCount(prev => prev + 1); // safe even in async contexts
Object state — spread to preserve other fields: ``jsx const [form, setForm] = useState({ name: '', email: '' }); setForm(prev => ({ ...prev, name: 'Alice' }));
State is per-instance — two <Counter /> components have independent state.
State updates are asynchronous — React batches updates. Reading count right after setCount gives the old value.
Examples
Toggle visibility
Boolean state is the simplest pattern for show/hide
function Collapsible({ title, children }) {
const [open, setOpen] = useState(false);
return (
<div>
<button onClick={() => setOpen(o => !o)}>
{open ? '▲' : '▼'} {title}
</button>
{open && <div>{children}</div>}
</div>
);
}Controlled input
Controlled inputs keep the input value in state — React is the single source of truth
function NameInput() {
const [name, setName] = useState('');
return (
<div>
<input
value={name}
onChange={e => setName(e.target.value)}
placeholder="Enter name"
/>
<p>Hello, {name || 'stranger'}!</p>
</div>
);
}How well did you understand this?
Next in React
Handling Events