Menu
Coddy logo textTech

Click Counter

Part of the Fundamentals section of Coddy's React journey — lesson 23 of 42.

State needs a trigger, usually an event. Wire a function to a button with onClick and change state inside it:

import { useState } from 'react';

export default function App() {
    const [count, setCount] = useState(0);
    return (
        <div>
            <button onClick={() => setCount(count + 1)}>+1</button>
            <p>{count}</p>
        </div>
    );
}

Follow one click around the loop: click → setCount(count + 1) → React re-renders → the paragraph shows the new count. Note the arrow function: onClick={() => setCount(count + 1)} passes a function to call later. Writing onClick={setCount(count + 1)} would call it immediately while rendering, a classic bug.

challenge icon

Challenge

Easy

Build the classic counter.

  1. Add state: count starting at 0 (the import is ready).
  2. Show the current count inside the span with id="count".
  3. Make the +1 button increase the count by 1 on every click.

Try it yourself

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="styles.css" />
    </head>
    <body>
        <div id="root"></div>
        <script type="module" src="main.jsx"></script>
    </body>
</html>
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals