useState is the most fundamental React Hook. It allows function components to store and update state, making UIs dynamic and interactive.
useState lets a component remember values between renders.
const [state, setState] = useState(initialValue)
It returns:
function Counter() {const [count, setCount] = useState(0)return (<button onClick={() => setCount(count + 1)}>{count}</button>)}
Clicking the button updates the state and re-renders the UI.
When new state depends on previous state:
setCount(prev => prev + 1)
This avoids bugs when updates happen quickly or in batches.
Always copy state instead of mutating it:
const [user, setUser] = useState({ name: "Daniel" })setUser(prev => ({ ...prev, name: "Alex" }))
setItems(prev => [...prev, newItem])
For expensive initial state:
const [value, setValue] = useState(() => computeInitial())
This runs only once, not on every render.
✔ Keep state minimal
✔ Prefer functional updates
✔ Split unrelated state
✔ Lift state when needed
✔ Avoid deeply nested state