useStateMachine: ½ kB state machine hook for React

Published on in JavaScript and React

A state machine is a bit like useReducer, but with greater constraints (in a good way). This state machine hook is tiny.

Cassio Zen's useStateMachine hook for React is a tiny (less than half a kilobyte) package for creating state machines. Pair it with Preact, and you have a very small yet powerful bundle for creating stateful UIs.

If you are not familiar with state machines, Cassio explains them in his YouTube video Getting your act together with State Machines (12:35).

State machines are somewhat similar to reducers. From one comment by Cassio under the video:

It's similar, but with one important distinction: with useReducer/redux you can always dispatch any action, and it will always reach the reducer. With state machines, the current state dictates which transitions you can "dispatch" next.

And this small change has a big impact because it empowers you to create your own constraints in the code to make a more robust application.

In the video, Cassio uses a popular state machine library called XState, but the main idea is the same. Sidenotes:

Two more good videos by Cassio on the topic: