Skip to content

Stopwatch with React State and Lifecycle Hooks

This version demonstrates using onLifecycle hooks instead of useEffect:

  • Uses lifecycle events to manage side effects
  • Provides better TypeScript autocompletion support
  • Constrains event types to their specific states

While slightly more verbose than other approaches, onLifecycle offers a superior developer experience with:

  1. Strong type inference for state and event-specific data
  2. Automatic documentation through IDE autocomplete
  3. Clear separation of lifecycle events by state

For example, in a configuration like { Rejected: { enter: ev => { ev.data.error } } }, TypeScript would correctly infer and autocomplete ev.error since it’s part of the Rejected state’s data.

import { defineStates, createMachine, assignEventApi } from "matchina";
export const createStopwatch = () => {
// Define states using defineStates
const states = defineStates({
Stopped: {},
Ticking: {},
Suspended: {},
});
// Create the base machine with states, transitions, and initial state
const baseMachine = createMachine(
states,
{
Stopped: {
start: "Ticking",
},
Ticking: {
stop: "Stopped",
suspend: "Suspended",
clear: "Ticking",
},
Suspended: {
stop: "Stopped",
resume: "Ticking",
clear: "Suspended",
},
},
"Stopped"
);
//Use assignEventApi to enhance the machine with utility methods
return assignEventApi(baseMachine);
};