Several State Variables

A component can have as many state variables as it needs: call useState once for each. They don't have to be numbers. Here's a vote that keeps a count and a text:

const [votes, setVotes] = useState(0);
const [lastVote, setLastVote] = useState("nobody yet");

function handleVote(name) {
    setVotes(votes + 1);
    setLastVote(name);
}

return (
    <main>
        <p>Votes: {votes}</p>
        <p>Last vote: {lastVote}</p>
        <button onClick={() => handleVote("Night Trains")}>Night Trains</button>
        <button onClick={() => handleVote("Lunar Cats")}>Lunar Cats</button>
    </main>
);

After a click on Lunar Cats, the page shows Votes: 1 and Last vote: Lunar Cats. One handler changed two state variables. React doesn't render after each setter: it waits until the handler has finished, and then renders once, with both new values.

Each state variable is separate. setVotes() changes only votes, and lastVote stays as it is. React tells them apart by the order in which the component calls useState, which is why hooks always go at the top of the component, called every time in the same order.

Not everything the page shows needs a state of its own. When a value can be worked out from the state you have, work it out while rendering:

const votesLeft = 5 - votes;

With <p>Votes left: {votesLeft}</p>, the page always shows the right number, because votesLeft is computed again on every render. A third state variable for it would only be one more thing to keep in step with the others, and one more place for a mistake.

Instructions

Give App two state variables, arrived and left, both starting at 0, and show them in the paragraphs. Someone arrived adds 1 to arrived, and Someone left adds 1 to left.

Under them, show how many people are at the festival now: At the festival: 2. Don't make it a third state. Compute it from arrived and left.

Start programming for free

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

Or sign up with:

Back

2/13

Next