How to Use useState in React (With Examples)

2025-06-12

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


Prerequisites

You should be familiar with:


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]

  1. Create a Counter component
  2. Initialize useState(0)
  3. Render a button that increments the count

Add extra features:


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!