Skip to content

Several Pieces of State

The Course
•
15 min study

A component can call useState as many times as it needs. Each call creates a separate piece of state with its own setter. This flashcard has two: whether the answer is showing, and the score.

A flashcard React · 3 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { useState } from "react"; export default function App() { const [showAnswer, setShowAnswer] = useState(false); const [score, setScore] = useState(0); return ( <main> <h1>Flashcard</h1> <section className="card"> <h2>What does useState return?</h2> {showAnswer && <p>An array: the current value and a function to change it.</p>} <button onClick={() => setShowAnswer(!showAnswer)}> {showAnswer ? "Hide answer" : "Show answer"} </button> </section> <p>Score: {score}</p> <button onClick={() => setScore(score + 1)}>I got it right</button> </main> ); } body { font: 16px/1.5 system-ui, sans-serif; margin: 0; color: #1c2430; } main { max-width: 32rem; margin: 1.5rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.75rem; } .card { border: 1px solid #d6dde6; border-radius: 8px; padding: 0.75rem 1rem; margin-bottom: 0.75rem; } .card h2 { margin: 0 0 0.25rem; font-size: 1.1rem; } .muted { color: #6b7785; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.

Toggling

JSX
<button onClick={() => setShowAnswer(!showAnswer)}>

! flips a true or false value, so each click switches between showing and hiding. The button's text uses the same state, through a ternary, so it always matches what's on screen.

Independent pieces

Click I got it right a few times, then show and hide the answer. Neither piece of state affects the other. Separate useState calls are the simplest choice when values change for different reasons.

Keep related values together, though. If two values always change at the same moment, such as an x and a y position, one state holding an object can be clearer. Day 4 covers objects and arrays in state.

What should be state?

Not every changing value needs to be state. Before adding one, ask:

  • Does it stay the same over time? Then it's a constant, not state.
  • Is it passed in by a parent? Then it's a prop.
  • Can you work it out from other state or props? Then compute it during render. For example, a percentage worked out from the score is a plain const, not a second piece of state.

Duplicated state goes out of step. If a percentage were stored as its own state, you'd have to remember to update it every time the score changed.

Your turn

Exercise

Count the attempts

Add an I got it wrong button. Track the number of attempts (right and wrong together) and show Score: 3 of 5 instead of Score: 3. Work out the percentage during render and show it in brackets, as Score: 3 of 5 (60%). Only show the percentage once there's at least one attempt.

Your working space React · 3 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { useState } from "react"; export default function App() { const [showAnswer, setShowAnswer] = useState(false); const [score, setScore] = useState(0); return ( <main> <h1>Flashcard</h1> <section className="card"> <h2>What does useState return?</h2> {showAnswer && <p>An array: the current value and a function to change it.</p>} <button onClick={() => setShowAnswer(!showAnswer)}> {showAnswer ? "Hide answer" : "Show answer"} </button> </section> <p>Score: {score}</p> <button onClick={() => setScore(score + 1)}>I got it right</button> </main> ); } body { font: 16px/1.5 system-ui, sans-serif; margin: 0; color: #1c2430; } main { max-width: 32rem; margin: 1.5rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.75rem; } .card { border: 1px solid #d6dde6; border-radius: 8px; padding: 0.75rem 1rem; margin-bottom: 0.75rem; } .card h2 { margin: 0 0 0.25rem; font-size: 1.1rem; } .muted { color: #6b7785; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.
Hint 1: the idea

The score and the number of attempts change on clicks, so they're state. The percentage can be computed from them, so it isn't.

Hint 2: a first step

I got it right increases both the score and the attempts. I got it wrong increases only the attempts.

Show one solution
JavaScript
const [score, setScore] = useState(0);
const [attempts, setAttempts] = useState(0);
const percent = attempts > 0 ? Math.round((score / attempts) * 100) : null;
JSX
<p>
  Score: {score} of {attempts}
  {percent !== null && ` (${percent}%)`}
</p>
<button onClick={() => { setScore(score + 1); setAttempts(attempts + 1); }}>
  I got it right
</button>{" "}
<button onClick={() => setAttempts(attempts + 1)}>I got it wrong</button>

percent is recalculated on every render, so it can never disagree with the score.

Was this article helpful?

Your response is saved on this device.