A Variable Isn't Enough
So far, the handlers have only printed. Now let's make a click change the page: a like button that counts likes. With what you know, you'd keep the number in a variable and increase it in the handler:
export default function App() {
let likes = 0;
function handleLike() {
likes = likes + 1;
console.log(likes);
}
return (
<main>
<h1>Owl Choir</h1>
<p>♥ {likes}</p>
<button onClick={handleLike}>Like</button>
</main>
);
}Click three times, and the console counts:
1
2
3But the page still shows ♥ 0. Why? React rendered the component once: it called App(), the function returned JSX in which likes was 0, and React made the page from it. Then the variable changed, but nobody told React. React doesn't watch your variables, and the page doesn't change by itself. In the JavaScript course, you'd now set textContent yourself. In React, you don't touch the page: React makes it from the components.
And even if React called App() again, it wouldn't help. The function would run from the top, and let likes = 0; would make a new variable with 0 again. A variable in a component lives only while the function runs, for one render.
So the component needs two things that a variable can't give it:
- a value that React keeps from one render to the next,
- and a way to tell React that the value has changed, so that it renders the component again.
That's state, and it's the next lesson. Try the problem for yourself first.
Instructions
Write a function handleLike that adds 1 to likes and then prints likes, and make it the click handler of the button Like. Click a few times: the console counts, and the page stays at ♥ 0.