Simple Counter Example
You'll learn: How to build a working counter that increments on button click using useState.
Bringing It All Together
Now that you've learned the pieces—useState, the setter function, and how state triggers re-renders—let's see them work together in a complete example. A counter is the classic first state demo because it's simple but demonstrates the full cycle: user interaction → state update → UI refresh.
The Counter Component
Here's how you build a basic increment counter:
function Counter() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
return (
<div>
<p>You clicked {count} times</p>
<button onClick={handleClick}>Click me</button>
</div>
);
}
What happens when you click the button:
- The
handleClickfunction runs setCount(count + 1)is called with the new value- React schedules a re-render
- The component function runs again
useState(0)returns the updated count value- The JSX displays the new number
Why This Works
The counter works because state persists between renders. Even though the Counter function runs from scratch each time, React remembers the current count value and gives it back to you when you call useState. Each click creates a new version of the UI with the updated number.
Key Takeaway: A simple counter demonstrates the complete useState cycle—initialize state, display it in JSX, update it with a setter, and see the UI automatically refresh with the new value.