Skip to content
Tutorials Center
My learning

Topics

Lesson 92 of 96 ยท Projects

Project: React Quiz with TypeScript

Build a quiz in React with TypeScript - a state machine reducer with a discriminated union, typed component props, event handler types and a live React demo you can edit.

React and TypeScript are a strong pair: props become a contract, state becomes a model, and every dispatch call is checked against the actions your reducer understands. In this project you build a small quiz app and focus on the TypeScript side of React: how to type state, actions, component props and event handlers.

It complements two other lessons. TypeScript with React covers each typing technique in isolation, and the React course's quiz project builds a larger quiz in JavaScript. Here you will see the types doing real work in a complete small app. For the non-React version of the same domain, see Project: Typed Quiz App.

The site can run TypeScript on a server and React in the browser, but not both at once, so the project is split into three pieces:

  1. The reducer, written in TypeScript and run here, because it is plain logic.
  2. The components, shown as read-only TSX (the real code you would write), plus a runnable stand-in that proves the props contracts.
  3. A live React demo you can edit. The browser editor runs JavaScript, so the demo is the same app with the type annotations removed. Read it side by side with the TSX: they differ only by types.

Stage 1: state, actions and the reducer

A quiz moves through phases: you are answering, then reviewing the result of your answer, and finally finished. Different phases need different data. While reviewing there is always a selected option; while finished there is no current question at all. A discriminated union gives each phase exactly its own fields, so impossible combinations (a finished quiz with a current index) cannot even be written.

Actions are also a union, tagged by type. The reducer must handle each one, and the assertNever helper in the default branch makes the compiler complain if you add an action and forget a case.

TypeScript Stage 1: a typed quiz reducer played without a UI

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Three things to notice:

  • Invalid actions are ignored by phase. check with nothing selected, or select while reviewing, returns the same state. In React, returning the same object tells useReducer that nothing changed, so there is no re-render.
  • Narrowing creates new states. After if (state.phase !== 'answering' || state.selected === null) return state;, the compiler knows state.selected is a number, which is exactly what the reviewing member requires. No assertions are needed.
  • The reducer is a pure function, so it is easy to test without React: feed it actions, check the state. A Vitest test would be five lines (see Testing TypeScript with Jest and Vitest).

Stage 2: typed components

In React with TypeScript, a component is a function from a props type to JSX. You describe the props with an interface or type alias. Here is the complete set of components as you would write them in Quiz.tsx. This code needs the real React and a bundler, so it is read-only:

TSX
import { useReducer, type ChangeEvent } from 'react';
import { initialState, reducer, QUESTIONS, type Question } from './quiz-state';

interface ProgressBarProps {
  current: number;
  total: number;
}

function ProgressBar({ current, total }: ProgressBarProps) {
  const percent = ((current + 1) / total) * 100;
  return (
    <div role="progressbar" aria-valuemin={1} aria-valuemax={total} aria-valuenow={current + 1}>
      <div style={{ width: `${percent}%` }} />
    </div>
  );
}

// Props as a discriminated union: "reviewing" has no onSelect, and "selected" is never null
type QuestionCardProps =
  | { mode: 'answering'; question: Question; selected: number | null; onSelect: (option: number) => void }
  | { mode: 'reviewing'; question: Question; selected: number };

function QuestionCard(props: QuestionCardProps) {
  const { question, selected } = props;
  return (
    <fieldset disabled={props.mode === 'reviewing'}>
      <legend>{question.prompt}</legend>
      {question.options.map((option, i) => (
        <label key={option}>
          <input
            type="radio"
            name={`q${question.id}`}
            checked={selected === i}
            onChange={(event: ChangeEvent<HTMLInputElement>) => {
              if (props.mode === 'answering' && event.target.checked) {
                props.onSelect(i); // narrowed: onSelect exists only in this mode
              }
            }}
          />
          {option}
          {props.mode === 'reviewing' && i === question.answer ? ' (correct)' : ''}
        </label>
      ))}
    </fieldset>
  );
}

interface ResultsProps {
  score: number;
  total: number;
  onRestart: () => void;
}

function Results({ score, total, onRestart }: ResultsProps) {
  return (
    <div>
      <h2>
        You scored {score} / {total}
      </h2>
      <button type="button" onClick={onRestart}>
        Try again
      </button>
    </div>
  );
}

export function QuizApp() {
  // The types of state and dispatch are inferred from the reducer's signature
  const [state, dispatch] = useReducer(reducer, initialState);

  if (state.phase === 'finished') {
    return <Results score={state.score} total={state.total} onRestart={() => dispatch({ type: 'restart' })} />;
  }

  const question = QUESTIONS[state.index]; // state.index exists here: phase is not 'finished'

  return (
    <div>
      <ProgressBar current={state.index} total={QUESTIONS.length} />
      {state.phase === 'answering' ? (
        <>
          <QuestionCard
            mode="answering"
            question={question}
            selected={state.selected}
            onSelect={(option) => dispatch({ type: 'select', option })}
          />
          <button type="button" disabled={state.selected === null} onClick={() => dispatch({ type: 'check' })}>
            Check answer
          </button>
        </>
      ) : (
        <>
          <QuestionCard mode="reviewing" question={question} selected={state.selected} />
          <button type="button" onClick={() => dispatch({ type: 'next' })}>
            Next
          </button>
        </>
      )}
    </div>
  );
}

Look at what the compiler is doing for you:

  • useReducer(reducer, initialState) infers state as QuizState and dispatch as (action: QuizAction) => void. A call like dispatch({ type: 'selct' }) fails to compile, and dispatch({ type: 'select' }) fails because option is missing.
  • Inside QuizApp, if (state.phase === 'finished') return ... narrows the state. After it, state.index exists, because the remaining members both have it. Remove the early return and state.index becomes an error.
  • In the reviewing branch, state.selected is a plain number, which QuestionCard in reviewing mode requires. Passing selected={null} there is a compile error.
  • onChange is typed with ChangeEvent<HTMLInputElement>, so event.target.checked is a boolean. You rarely need to write that annotation, since inline arrow functions get the event type by contextual typing; it is shown here for clarity.
  • Props are destructured in the parameter list with their interface. You do not need React.FC; plain functions are simpler and play better with generics.

The following stand-in runs the same props contracts as ordinary functions that return text. It proves the types accept valid props and reject invalid ones:

TypeScript Stage 2: typed props, valid and invalid

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The union props are the part to study. QuestionCard in reviewing mode literally cannot receive an onSelect, because a reviewing card has nothing to select. Passing the wrong combination is a compile error, which means a whole category of "this prop does nothing in this state" bugs disappears. Compare that with a single interface where onSelect? is optional: it compiles with every combination and you find out at runtime.

Stage 3: the live React demo

Now the real thing running in your browser. The demo below is the same app as the TSX above, assembled in one editor: it has the same reducer, the same ProgressBar, QuestionCard and Results components and the same QuizApp. It is plain JSX, because the in-browser editor does not type check. Answer a few questions, check them, and watch the phases change.

The quiz running in React

How does the typed version differ from the demo? Three places:

  1. QuizState, QuizAction, Question and the props interfaces are removed (types are erased at compile time).
  2. The state is no longer a union per phase, so the demo keeps index and selected in every phase and checks state.phase by hand. The typed version cannot have those mistakes.
  3. The onChange handler needs no annotation.

When you move the demo into a real project, the compiler turns "I hope I handled every case" into "I know I did".

Project structure for a real app

A typical layout for this app in a Vite project:

TEXT
src/
  quiz-state.ts      the Question type, QuizState, QuizAction, reducer, QUESTIONS
  quiz-state.test.ts reducer tests (no React needed)
  Quiz.tsx           ProgressBar, QuestionCard, Results, QuizApp
  main.tsx           createRoot(document.getElementById('root')!).render(<QuizApp />)

The ! after getElementById is a non-null assertion. It is the usual way to tell TypeScript the root element exists. If you prefer a safe check, write const root = document.getElementById('root'); if (!root) throw new Error('Missing #root');.

Testing the reducer needs no React, no DOM and no mocks:

TypeScript
import { describe, expect, it } from 'vitest';
import { initialState, reducer } from './quiz-state';

describe('quiz reducer', () => {
  it('ignores check when nothing is selected', () => {
    expect(reducer(initialState, { type: 'check' })).toBe(initialState);
  });

  it('moves to reviewing and scores a correct answer', () => {
    const selected = reducer(initialState, { type: 'select', option: 2 });
    const checked = reducer(selected, { type: 'check' });
    expect(checked.phase).toBe('reviewing');
    expect(checked.score).toBe(1);
  });
});

Ideas to extend it

  • Add a countdown per question with an Effect (the React quiz project shows the pattern) and a { type: 'timeout' } action.
  • Make questions a discriminated union (single, multiple, text) as in Project: Typed Quiz App, and give QuestionCard a union of props to match.
  • Load questions from an API and model the loading state: { status: 'loading' } | { status: 'ready'; questions: Question[] } | { status: 'error'; message: string }.
  • Add a generic <Select<T>> component, following the generic components section of TypeScript with React.
  • Provide the state through Context with a custom useQuiz hook that throws if used outside its provider, so consumers never see undefined.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why model the quiz state as a union with one member per phase?

    For example, a finished state has no index, and a reviewing state always has a selected number.
  2. 2. What does useReducer(reducer, initialState) infer in TypeScript?

    The generic parameters come from the reducer function's signature, so dispatch rejects unknown actions.
  3. 3. What is the advantage of QuestionCardProps being a discriminated union?

    The mode tag selects the member, and excess or missing props are reported per member.
  4. 4. Why does returning the same state object for an invalid action matter?

    useReducer bails out when the new state is the same reference as the old one.
  5. 5. Why is the live demo plain JSX instead of TSX?

    Types are erased at build time. The demo shows the runtime behavior; the TSX shows what the compiler checks.

Summary

  • Model the quiz as a discriminated state union and a discriminated action union; the reducer is a pure function with an exhaustive switch.
  • useReducer infers state and dispatch from the reducer, so wrong actions fail to compile.
  • Type component props with interfaces; use a union of props when a component has distinct modes.
  • Narrowing on state.phase in the component unlocks exactly the fields valid in that branch.
  • Return the same state object for ignored actions to avoid needless renders, and test the reducer without React.
  • The runnable demo is the same app without types; types exist only in the editor and compiler.

Next: TypeScript Cheat Sheet