Your First State

At the end of the last lesson, the page didn't change: React didn't know that likes had changed, and each render would start it from 0 again. What fixes it is state, a value that React keeps for the component. You make it with useState:

import { useState } from "react";

export default function App() {
    const [likes, setLikes] = useState(0);

    function handleLike() {
        setLikes(likes + 1);
    }

    return (
        <main>
            <h1>Owl Choir</h1>
            <p>♥ {likes}</p>
            <button onClick={handleLike}>Like</button>
        </main>
    );
}

Now each click adds 1, and the page shows it. Line by line:

  • useState is a function of React. Import it at the top of the file, in curly braces, as you import named exports.
  • useState(0) gives the component a state that starts at 0. It returns an array of two things, which you destructure into constants: likes, the value now, and setLikes, the function that changes it. You choose the names. It's usual to call them something and setSomething.
  • setLikes(likes + 1) tells React the new value. React then renders the component again: it calls App() once more, and this time useState(0) returns 1, because the starting value is only used the first time. The JSX now has ♥ 1, and React changes the paragraph on the page to match.

So it's always the same order: an event, a handler that calls a setter, a new render with the new value, and a page that shows it. You never change the page yourself.

Functions of React whose names start with use, like useState, are called hooks. Call them at the top of the component, before anything else, and never inside an if, a loop or a handler. You'll meet more hooks later in the course.

Typical mistakes:

  • likes = likes + 1 or likes++ in the handler. likes is a constant, so the console says TypeError: Assignment to constant variable. And even if it weren't, React wouldn't know. Only the setter changes state.
  • No import of useState. The page stays empty, and the console says ReferenceError: useState is not defined.

Instructions

Replace the variable likes with state, so that each click on Like adds 1 to the number on the page. (You can delete the console.log().)

Add a button Reset after Like, which sets the likes back to 0.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

Back

1/13

Next