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
EasyBuild the classic counter.
- Add state:
countstarting at0(the import is ready). - Show the current count inside the span with
id="count". - Make the
+1button 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>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
2JSX Expressions
Curly BracesMath in BracesBraces in AttributesCalling Functions in JSXRecap: JSX Expressions5State & Events
What Is State?Click CounterCount in StepsToggle with StateIndependent StateRecap: State & Events8Project: Profile Card
Step 1: Card StructureStep 2: Card with PropsStep 3: Like ButtonStep 4: Follow Toggle