React
Beginner
2 min read
useState Hook Basics
Example
import { useState } from 'react';
// 1. Basic counter
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>
<button onClick={() => setCount(0)}>Reset</button>
</div>
);
}
// 2. Updater function form (safe for async / batched updates)
function SafeCounter() {
const [count, setCount] = useState(0);
const incrementThrice = () => {
// All three updates are batched — using updater ensures correct result
setCount(c => c + 1);
setCount(c => c + 1);
setCount(c => c + 1);
// Without updater form, all three would read the same stale `count`
};
return <button onClick={incrementThrice}>+3 (now: {count})</button>;
}
// 3. Lazy initialisation — function runs only once
function LocalStorageCounter() {
const [count, setCount] = useState(() => {
const stored = localStorage.getItem('count');
return stored ? Number(stored) : 0;
});
const increment = () => {
const next = count + 1;
setCount(next);
localStorage.setItem('count', next);
};
return <button onClick={increment}>Persisted count: {count}</button>;
}
export default Counter;