State with useState
State is what makes React components interactive. Unlike props, state can change over time.
Props vs State
| Props | State |
|---|---|
| Passed from parent | Managed within component |
| Read-only | Can be updated |
| Like function arguments | Like local variables that trigger re-renders |
The useState Hook
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
// ^ ^ ^
// | | initial value
// | updater function
// current value
return (
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}
Rules of useState
- Call at top level - Not inside loops, conditions, or nested functions
- Call in React functions - Only in components or custom hooks
- Use the setter - Never modify state directly:
count = 5❌
State Updates Trigger Re-renders
When you call setCount, React:
- Updates the state value
- Re-renders the component
- Shows the new UI
Try the interactive state examples below!