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.
npm install and npm run dev. Toggling
<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
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.
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
const [score, setScore] = useState(0);
const [attempts, setAttempts] = useState(0);
const percent = attempts > 0 ? Math.round((score / attempts) * 100) : null;<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.
Completion is saved in this browser only. It does not measure mastery.