How to Use useState
in React (With Examples)
New to React? In this guide, you’ll learn how useState
works and use it to build a real, working counter app — all explained simply.
What You’ll Learn
- What
useState
is and when to use it - How to build a simple stateful component
- Common
useState
pitfalls to avoid
Prerequisites
You should be familiar with:
- Basic JavaScript syntax
- React component structure (functional components)
The Concept Explained
React’s useState
lets you add state to functional components. Here’s the syntax:
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}
When the button is clicked, setCount
updates the state and React re-renders the component.
Hands-On Project: Build a Counter
Try this live: [CodeSandbox Embed Here]
- Create a
Counter
component - Initialize
useState(0)
- Render a button that increments the count
Add extra features:
- ✅ A reset button
- ✅ Disable button when count hits 10
Common Mistakes
❌ Putting useState
inside a loop or condition
// ❌ This will break
if (someCondition) {
const [count, setCount] = useState(0);
}
✅ Always call hooks at the top level of your component.
Try It Yourself!
Add a “Decrement” button that subtracts from the count.
Bonus: Show a warning if count < 0
What’s Next?
🎯 Next in the series: Understanding useEffect
📬 Want weekly React tips + mini-projects? Join the email list here
👍 Was this helpful? Let me know on Twitter!