Skip to content
Tutorials Center
My learning

Topics

Lesson 105 of 132 ยท Projects

Project: Quiz App

Build a timed quiz app in React: model the flow as a state machine with useReducer, run a countdown in an effect with cleanup, show the score and add a review mode.

A quiz looks like a pile of screens: a welcome page, one question at a time, a score, and a look back at what you got wrong. The trap for beginners is to track each screen with its own boolean (showIntro, showScore, isReviewing...). Soon two of them are true at once and the app shows something impossible. In this project you will avoid that by modelling the quiz as a state machine, one clearly named status at a time, driven by a reducer.

Along the way you will practise most of what the Hooks chapters taught: useReducer, derived state, an Effect with cleanup for a countdown timer, useEffectEvent, and keys that reset state. Everything is built in four stages, and each runnable stage is complete.

Step 0: the data and the states

The questions are plain data. Each has a prompt, the options, the index of the correct option (0-based, as JavaScript arrays are) and a short explanation to show afterwards.

JavaScript
const QUESTIONS = [
  {
    prompt: 'Which hook stores a value that survives re-renders and triggers a new render when it changes?',
    options: ['useRef', 'useState', 'useMemo', 'useId'],
    correct: 1,
    explanation: 'useState keeps the value between renders and re-renders on change; useRef does not re-render.',
  },
  // ...more questions
];

Now list the screens as statuses:

Status What the user sees Leaves when
intro Title and a Start button The user presses Start
playing One question, options, a timer The last question is answered and "Next" is pressed
finished The score and two buttons The user chooses Review or Try again
review Every question with the right answer The user chooses Try again

Only one row can be true at a time, which is exactly what a single status string guarantees. The other facts we need are the current question index and the list of answers given so far. Everything else is derived: the question being shown is QUESTIONS[index], "answered" means answers.length > index, and the score is the number of answers equal to the correct option. We never store the score, because storing it creates a second source of truth that can disagree with answers.

Step 1: the reducer, tested on its own

The reducer is the whole brain of the app. Actions are named after what happened: started, answered, advanced, reviewed, restarted.

JavaScript
function quizReducer(state, action) {
  switch (action.type) {
    case 'started':
      return { status: 'playing', index: 0, answers: [] };
    case 'answered':
      if (state.status !== 'playing' || state.answers.length > state.index) {
        return state;
      }
      return { ...state, answers: [...state.answers, action.choice] };
    case 'advanced':
      if (state.status !== 'playing' || state.answers.length <= state.index) {
        return state;
      }
      return state.index + 1 === action.total
        ? { ...state, status: 'finished' }
        : { ...state, index: state.index + 1 };
    case 'reviewed':
      return state.status === 'finished' ? { ...state, status: 'review' } : state;
    case 'restarted':
      return initialState;
    default:
      throw new Error('Unknown action: ' + action.type);
  }
}

Read the guards. An answered action is ignored unless the quiz is playing and the current question has no answer yet, so a double click or a timer that fires after a click cannot record two answers. advanced refuses to move on until the current question was answered. These checks turn illegal transitions into harmless no-ops, which is the main benefit of a state machine; the lesson on state machines goes deeper.

A choice of null will mean "time ran out". The reducer does not care; it just stores what it is given.

Stage 1: play the quiz without a UI

The first advanced is ignored because the quiz has not started. The second answered is ignored because question 0 already has an answer. And the quiz only reaches finished after the final question is answered and advanced, so the last reviewed works. You just tested the full flow with zero UI.

Step 2: the question flow

Now render each status. A small Quiz component reads the state and picks a screen; the screens are separate components, each receiving only what it needs. The score is computed with reduce during render.

After a choice, the options lock and show which one was right. That is derived from state too: answered is answers.length > index and the chosen option is answers[index]. We need no selected or isLocked variable.

Stage 2: the quiz without the timer

Play it through, and notice what is missing from the component: there is no useState at all. The reducer is the only state, and the screens are pure functions of it. When you later add review mode, you add one status and one screen, and nothing existing needs to change.

Step 3: a countdown with an Effect

A timer is the first piece of this app that talks to something outside React: the browser's clock. That is the textbook use of an Effect. The requirements are:

  • Every question starts with a fresh countdown.
  • The countdown stops when the player answers.
  • When it reaches zero, the app records a "no answer" (null) for that question.
  • Leaving the screen must stop the interval, or it keeps ticking in the background.

The first requirement has an elegant solution that needs no reset code: render the timer with key={state.index}. A different key makes React unmount the old Countdown and mount a new one, so its state starts at the full time again. This is the "reset state with a key" technique from lists and keys.

Inside Countdown, one Effect owns the interval. It starts when running is true and its cleanup clears the interval; React runs the cleanup before the Effect runs again and when the component unmounts.

JSX
useEffect(() => {
  if (!running) {
    return;
  }
  const id = setInterval(() => setLeft((value) => value - 1), 1000);
  return () => clearInterval(id);
}, [running]);

The tick uses the functional form value - 1, so the Effect does not depend on left and the interval is not recreated every second. A second Effect watches for zero. It must call the onExpire callback, but onExpire is a new function on every render of the parent, and listing it as a dependency would restart the Effect constantly. That is the job of useEffectEvent: it wraps a callback so the Effect can read the latest version without depending on it. See useEffectEvent for the full rules.

Do not call dispatch inside the function you pass to setLeft. State updater functions must be pure and React may run them twice in development. Detect zero in an Effect or in an event, never inside an updater.

Stage 3: a countdown that resets for each question

Press Start, answer quickly, then watch the next question's clock begin at 5 again. Next, do nothing on a question and wait: when the clock reaches 0 the app records a timeout and offers "Time is up. Continue". The console shows interval cleared each time a countdown stops: when you answer (because running became false), when time runs out, and when a question's Countdown is replaced by the next one.

Step 4: results and review mode

For the final stage add the two missing pieces. A finished screen gets a percentage and a "Review answers" button. A new review status shows every question with your answer, the right answer and the explanation. Because answers are stored as indexes, the review screen is a map over QUESTIONS that reads answers[i]; a null prints "No answer (time ran out)".

The reducer gets one more case, reviewed, which only works from finished. Percentages are derived with Math.round, never stored. The timer constant is short (4 seconds) so you can see a timeout quickly.

Stage 4: the complete quiz with review

Ideas to extend it

  • Shuffle the options with a seeded shuffle done once when the quiz starts, and store the shuffled order in state. Never call Math.random() while rendering.
  • Keyboard shortcuts: number keys 1 to 4 choose an option, using a keydown listener in an Effect with cleanup (effect cleanup).
  • Load questions asynchronously: add a loading status and fetch in an Effect or with use() (data fetching).
  • Accessibility: announce the result to screen readers with role="status"; the timer here uses role="timer". See accessibility.
  • Difficulty levels: add difficulty to the state and filter QUESTIONS once, when starting.

What you practised

Think back over the design instead of the details. One status string made impossible screens impossible. The reducer ignored out-of-order actions instead of trusting the UI. Score, percentage, "answered" and "is last" were all derived from answers and index. The timer, the only code that touches the outside world, lives in one small component whose Effect starts and stops the interval, and key gives each question a fresh clock. Those four habits carry over to checkout flows, wizards and any other multi-step interface.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the quiz use a single status string instead of several booleans such as showIntro and showScore?

    With several booleans you must keep them consistent by hand and can end up showing two screens at once. One status makes the screen a function of a single value.
  2. 2. The score is not stored in state. Why?

    Anything you can derive from existing state should be derived. A stored score could drift away from the actual answers.
  3. 3. What does key={state.index} on the Countdown component achieve?

    A changed key makes React unmount the old component and mount a new one. State starts over, and the old Effect cleanup clears the previous interval.
  4. 4. Why is the expiry callback wrapped with useEffectEvent?

    onExpire is a new function every render. If it were an Effect dependency, the Effect would re-run constantly. An Effect Event always sees the latest props and state but is not reactive.
  5. 5. A player clicks an option at the exact moment the timer expires, so both 'answered' actions arrive. What happens?

    The reducer's guard compares answers.length with index. After the first answer the condition is true and the second action returns the same state.

Summary

  • Model multi-screen flows as a state machine: one status string plus the minimal data, and a reducer that ignores illegal transitions.
  • Derive the current question, "answered", the score and the percentage during render instead of storing them.
  • Test the reducer as a plain function before building the UI; it is the easiest and fastest test you will write.
  • Put the timer in a small component with one Effect whose cleanup clears the interval, tick with the functional updater, and use key to reset it for each question.
  • Use useEffectEvent when an Effect must call the latest callback without re-running whenever that callback changes.
  • Add features such as review mode by adding a status, a reducer case and a screen, not by patching existing code.

Next: Project: Search with Debounce and Suspense