State: A Counter
Give a component memory, and click a real button to change it.
1import { useState } from 'react';
2
3function App() {
4 const [count, setCount] = useState(0);
5 return (
6 <button onClick={() => setCount(count + 1)}>
7 Clicked {count} times
8 </button>
9 );
10}
11export default App;
$ npm run dev
VITE v5.4 ready in 312 ms
Local: http://localhost:5173/
(your app is live: look at the browser window above!)
Every line, explained
import { useState } from 'react';- useState comes from the React library itself. This locked import line brings it in; you'll use it a few lines down.
function App() {- The App component: every lesson's page starts from this function.
const [count, setCount] = useState(0);- State is a component's memory. useState(0) creates a piece of state starting at 0 and hands back a pair, unpacked by the square brackets (a cousin of lesson 4's curly-brace trick: brackets grab the two values in order, and you choose their names): count (the current value) and setCount (the only proper way to change it). When you call setCount, React re-runs your function and redraws the screen with the new value. That loop is the engine of every React app.
return (- When JSX spans several lines, it goes inside round brackets after return. The brackets keep the JSX attached to the return: without them, JavaScript would think the return finished at the end of that line and hand back nothing.
<button onClick={() => setCount(count + 1)}>- A <button> with a click handler: onClick={...} takes an arrow function to run on every click. This one calls setCount(count + 1), so each click bumps the memory up by one and triggers a redraw.
Clicked {count} times- The button's label reads the state, so the label updates on every redraw. TRY IT: the button in the browser window really works once the program runs!
</button>- Close the button tag.
);- The ); closes the return's round bracket.
}- This } closes the component function.
export default App;- export default App hands your component to the rest of the app. A locked line in every lesson: the app's starter file (main.jsx) imports App and mounts it on the page.