useState
Adding interactivity — state, re-renders, functional updates, and derived values
Skills taught: react.useState, react.re-renders, react.state-updates, react.functional-updates, react.derived-state
useState basics
function Counter() {
const [count, setCount] = useState(0); // initial value: 0
return (
<div style={{ fontFamily: 'sans-serif', padding: '8px' }}>
<h2>Count: {count}</h2>
<div style={{ display: 'flex', gap: '8px' }}>
<button onClick={() => setCount(count + 1)}>+1</button>
<button onClick={() => setCount(count - 1)}>−1</button>
<button onClick={() => setCount(0)}>Reset</button>
</div>
</div>
);
}
// State is LOCAL — two Counters are independent
function App() {
return (
<>
<Counter />
<Counter />
</>
);
}
// Toggle state
function Toggle() {
const [isOn, setIsOn] = useState(false);
return (
<button
onClick={() => setIsOn(prev => !prev)} // functional update
style={{ background: isOn ? '#4fd1c5' : '#e2e8f0', padding: '8px 16px', border: 'none', borderRadius: '20px', cursor: 'pointer' }}
>
{isOn ? 'ON ✓' : 'OFF'}
</button>
);
}
// Object state — spread to avoid mutation
function ProfileForm() {
const [user, setUser] = useState({ name: '', email: '', age: '' });
const updateField = (field, value) => {
setUser(prev => ({ ...prev, [field]: value })); // spread + update one field
};
return (
<div style={{ fontFamily: 'sans-serif', padding: '8px', display: 'flex', flexDirection: 'column', gap: '8px', maxWidth: '300px' }}>
<input placeholder="Name" value={user.name} onChange={e => updateField('name', e.target.value)} style={{ padding: '6px', borderRadius: '4px', border: '1px solid #d1d5db' }} />
<input placeholder="Email" value={user.email} onChange={e => updateField('email', e.target.value)} style={{ padding: '6px', borderRadius: '4px', border: '1px solid #d1d5db' }} />
<pre style={{ background: '#f3f4f6', padding: '8px', borderRadius: '4px', fontSize: '0.8rem' }}>{JSON.stringify(user, null, 2)}</pre>
</div>
);
}
function App() {
return (
<div style={{ padding: '8px', display: 'flex', flexDirection: 'column', gap: '12px' }}>
<Toggle />
<ProfileForm />
</div>
);
}
Frequently Asked Questions
Why can't I mutate state directly? (e.g., `count++` or `user.name = 'Bob'`)
Direct mutation doesn't trigger a re-render — React doesn't know the value changed. You must call the setter: setCount(count + 1) or setUser({...user, name: 'Bob'}). For objects and arrays, always create a new copy (spread operator or map/filter) rather than mutating the existing value. React compares references — if the reference hasn't changed (mutation), it sees 'no change' and skips re-rendering.