6 minImpossible States, part 3

Prevent Impossible States Pt. 3 - A UI Driven by State

Use the timer's state machine to drive a React UI, with controls that match its current status.

Introduction

In an attempt to flex my full-stack muscles, I have been spending time putting out content centered around using TypeScript to build deterministic software. Thus far, I’ve discussed using discriminated unions, and demonstrated how to apply union types to create finite state machines. In this post, we’ll bring the view layer into the mix.

To recap: our goal for using state machines is to ensure our application code is protected from invalid or “impossible” states. An example of an impossible state might be seeing a “sign in” button in an application that you’re already logged in to. This causes confusion, and adds noise to user flows that we’re obligated to make as frictionless as possible.

Recapping TimerState and TimerEvent

I previously laid out the TimerState and TimerEvent types shown below.

type TimerState =
  | { status: 'idle' }
  | { status: 'running'; remainingSeconds: number }
  | { status: 'paused'; remainingSeconds: number }
  | { status: 'finished' };

type TimerEvent =
  | { type: 'start'; durationSeconds: number }
  | { type: 'pause' }
  | { type: 'resume' }
  | { type: 'tick' }
  | { type: 'reset' };

These are the state and event values that will be passed into the transition function.

type Transition = (state: TimerState, event: TimerEvent) => TimerState;

The full implementation is in Pt. 2, and in the timer.ts tab of each sandbox below.

With that, we can move forward with connecting this logic to our UI. While this example might seem fairly barebones, it still demonstrates an important practice of isolating business logic from the view logic to ensure our UI is deterministic.

Defining our state map

Before we wire up our UI, let’s sketch out how everything should function. The table below explicitly defines the “status → control” relationship for each state.status option.

StatusControls
idleStart
runningPause, Reset
pausedResume, Reset
finishedReset

When state.status is idle, our view will enforce that only the “Start” control is rendered. When state.status is running, our view will enforce that “Pause” and “Reset” controls are rendered. And so on.

Connecting the timer to React

The transition function is already in the correct shape to be passed into React’s useReducer API. In return, we’ll get the state, which will give us the status, remainingSeconds, etc., and a dispatch function we’ll use to send our TimerEvents.

Timer.tsxTypeScript 5.9.3 · React 19.3.1 · strict · with timer.ts
import { useReducer } from 'react';
import { transition, type TimerState } from './timer';

const initialState: TimerState = { status: 'idle' };

export const Timer = () => {
  const [state, dispatch] = useReducer(transition, initialState);

  return (
    <section>
      <p>Status: {state.status}</p>
      {state.status === 'idle' ? (
        <button
          onClick={() => dispatch({ type: 'start', durationSeconds: 30 })}
        >
          Start
        </button>
      ) : null}
    </section>
  );
};

Starting the timer changes the displayed status and removes the “Start” button. The click handler only sends the event and the transition rules stay in transition.

Rendering the controls for each state

We know that each control needs to dispatch its corresponding event, so we can abstract that shared logic into a ControlButton component.

import type { Dispatch } from 'react';
import type { TimerEvent } from './timer';

export type TimerControlProps = {
  event: TimerEvent;
  label: string;
  dispatch: Dispatch<TimerEvent>;
};

export const ControlButton = ({ event, label, dispatch }: TimerControlProps) => (
  <button type="button" onClick={() => dispatch(event)}>
    {label}
  </button>
);

Dispatch<TimerEvent> describes a function that accepts a TimerEvent. We’ll wire our component up to invoke it onClick, so dispatch runs when the user clicks. TimerView is what we’ll use to determine which ControlButtons are rendered.

Catching a missing view

What if we forget to handle the paused state? We can use the same exhaustiveness check we used in our transition function. Here’s a shorter view that returns status text, with the paused case deliberately left out:

A missing paused viewTypeScript 5.9.3 · strict · with timer.ts
import type { TimerState } from './timer';

// This view returns status text. It deliberately leaves out 'paused'.
const TimerStatus = ({ state }: { state: TimerState }): string => {
  switch (state.status) {
    case 'idle':
      return 'Ready to start';
    case 'running':
      return `Running: ${state.remainingSeconds} seconds remaining`;
    case 'finished':
      return 'Timer finished';
    default: {
      const unreachable: never = state;
      return unreachable;
    }
  }
};

// Add a 'paused' case above the default, returning the paused status text.
console.log(TimerStatus({ state: { status: 'running', remainingSeconds: 20 } }));

At const unreachable: never = state, TypeScript reports:

Type '{ status: "paused"; remainingSeconds: number; }' is not assignable to type 'never'.

We’ve handled the other three statuses, so state can still be a paused timer when it reaches default. Adding this case before default clears the error:

case 'paused':
  return `Paused: ${state.remainingSeconds} seconds remaining`;

This checks that we’ve handled every status. It doesn’t check that we’ve included the right buttons inside each case. If we handle paused but forget its “Resume” button, that still type-checks.

Rendering the buttons

The full component uses that same check. In TimerView.tsx:

TimerView.tsxTypeScript 5.9.3 · React 19.3.1 · strict · with timer.ts, Timer.tsx, ControlButton.tsx
import type { Dispatch } from 'react';
import type { TimerEvent, TimerState } from './timer';
import { ControlButton } from './ControlButton';

type TimerViewProps = {
  state: TimerState;
  dispatch: Dispatch<TimerEvent>;
};

export const TimerView = ({ state, dispatch }: TimerViewProps) => {
  switch (state.status) {
    case 'idle':
      return (
        <ControlButton
          label="Start"
          event={{ type: 'start', durationSeconds: 30 }}
          dispatch={dispatch}
        />
      );

    case 'running':
      return (
        <section>
          <p>Running: {state.remainingSeconds} seconds remaining</p>
          <ControlButton label="Pause" event={{ type: 'pause' }} dispatch={dispatch} />
          <ControlButton label="Reset" event={{ type: 'reset' }} dispatch={dispatch} />
        </section>
      );

    case 'paused':
      return (
        <section>
          <p>Paused: {state.remainingSeconds} seconds remaining</p>
          <ControlButton label="Resume" event={{ type: 'resume' }} dispatch={dispatch} />
          <ControlButton label="Reset" event={{ type: 'reset' }} dispatch={dispatch} />
        </section>
      );

    case 'finished':
      return (
        <section>
          <p>Timer finished</p>
          <ControlButton label="Reset" event={{ type: 'reset' }} dispatch={dispatch} />
        </section>
      );

    default: {
      const unreachable: never = state;
      return unreachable;
    }
  }
};

We’re ready to update our Timer component so it passes the current state and dispatch to that view:

Timer.tsxTypeScript 5.9.3 · React 19.3.1 · strict · with timer.ts, TimerView.tsx, ControlButton.tsx
import { useReducer } from 'react';
import { transition, type TimerState } from './timer';
import { TimerView } from './TimerView';

const initialState: TimerState = { status: 'idle' };

export const Timer = () => {
  const [state, dispatch] = useReducer(transition, initialState);

  return <TimerView state={state} dispatch={dispatch} />;
};

We’re using our state machine to deterministically render the UI, so we don’t need separate state variables to track whether “Pause” or “Resume” should appear.

Our transition function is our API for managing the timer’s state. If someone clicks “Pause”, we send a pause event and let the function determine the next state. We’re keeping our business logic out of the view. The view can just take the values it needs to show the appropriate controls.

Isolating clock logic into a custom hook

Right now the timer shows its remaining time but never counts down, so it needs a clock.

I’ve historically been very anti-useEffect (as per guidance from the React team). In production systems, I’ll reach for a state management library, or something like TanStack Query to handle my async logic. Regardless of how it’s done, the goal of keeping application logic separate from my view code remains the same. For this example, though, a small useEffect isolated in a custom hook will have to do.

We keep that subscription in a custom hook, separate from the view.

useTimer.tsTypeScript 5.9.3 · React 19.3.1 · strict · with timer.ts, TimerView.tsx, Timer.tsx, ControlButton.tsx
import { useEffect, useReducer } from 'react';
import { transition, type TimerState } from './timer';

const initialState: TimerState = { status: 'idle' };

export const useTimer = () => {
  const [state, dispatch] = useReducer(transition, initialState);

  useEffect(() => {
    if (state.status !== 'running') return;

    const intervalId = setInterval(() => dispatch({ type: 'tick' }), 1000);
    return () => clearInterval(intervalId);
  }, [state.status, dispatch]);

  return { state, dispatch };
};

In useTimer.ts, useReducer manages the state, and useEffect sends a tick event every second while the status is running. With that in place, we can update Timer to call useTimer(). This Effect only synchronizes with the browser clock, so our rendering logic still derives directly from state. It depends on state.status and dispatch, so updating remainingSeconds doesn’t restart the interval.

Clicking the “Run” button in the sandbox below should display our finished Timer. Go on, give it a try.

Timer.tsxTypeScript 5.9.3 · React 19.3.1 · strict · with timer.ts, TimerView.tsx, useTimer.ts, ControlButton.tsx
import { useTimer } from './useTimer';
import { TimerView } from './TimerView';

export const Timer = () => {
  const { state, dispatch } = useTimer();

  return <TimerView state={state} dispatch={dispatch} />;
};

As expressed in our transition function, the next tick after state.remainingSeconds reaches 1 returns { status: 'finished' }, causing the view to update so that only “Reset” is available.

Adding more timers

We’ve contained the beast, so to speak. Before we wrap up, let’s enjoy the fruits of our labor and see how quickly we can extend our code so that users can create multiple timer widgets, each with its own controls.

Each Timer calls useTimer, so each instance has its own state. Sending a pause or a reset event to one won’t change the state of a second or third timer - each is totally independent, just as we intended.

In Timers.tsx:

Timers.tsxTypeScript 5.9.3 · React 19.3.1 · strict · with timer.ts, TimerView.tsx, Timer.tsx, useTimer.ts, ControlButton.tsx
import { useState } from 'react';
import { Timer } from './Timer';

export const Timers = () => {
  const [timerIds, setTimerIds] = useState<string[]>([]);

  const createTimer = () => {
    const id = crypto.randomUUID();
    setTimerIds(ids => [...ids, id]);
  };

  return (
    <section>
      <button type="button" onClick={createTimer}>Create timer</button>
      <ul>
        {timerIds.map((id, index) => (
          <li key={id}>
            <h2>Timer {index + 1}</h2>
            <Timer />
          </li>
        ))}
      </ul>
    </section>
  );
};

The parent keeps track of which timers exist. Each timer keeps track of its own status and remaining time. We create each ID when the user clicks the button and keep it as a stable key, so React can identify the existing timers when we add another one.

Try creating two timers, starting both, and pausing or resetting just one. The other timer should keep its state.

What this does not solve yet

The exhaustiveness check makes sure every status has a view. It doesn’t make sure each view is right. If the paused case drops its “Resume” button, everything still type-checks, and the user is stuck with a timer they can only reset. The table at the top of this post is our spec, and right now nothing checks the view against it. A component test for each status would close that gap.

The lesson

In the intro, I used a “sign in” button on a page you’re already logged in to as an example of an impossible state. That bug usually comes from the UI keeping its own copy of the truth: an isLoggedIn flag in one place, a showSignIn flag in another, and eventually they disagree.

Our timer’s view doesn’t keep a copy. It reads state.status and renders the controls for that status. Nothing else.

Each post in this series added one piece:

  • Pt. 1: discriminated unions define the shapes our state can take.
  • Pt. 2: the transition function defines which changes between those shapes are allowed.
  • Pt. 3: the view renders only the actions the current state allows.

That gives us two layers of protection. The UI only offers valid actions, and if an invalid event gets sent anyway, like pause while the timer is idle, transition leaves the state alone. It’s also why adding more timers only took one small component. The rules didn’t change, so we didn’t have to touch them.

Thomas Greco writes about software engineering, life, and what he’s learning and building.