Course contentsShow
← React
Lesson 338 of 2,39610. useState BasicsFree lesson

Simple Counter Example

Building a basic counter to see useState in action with increment functionality.

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:

  1. The handleClick function runs
  2. setCount(count + 1) is called with the new value
  3. React schedules a re-render
  4. The component function runs again
  5. useState(0) returns the updated count value
  6. 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.