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:
- XState is more featureful,
but also weighs more,
about 19 kB
(including the
@xstate/react
package required by React). Other differences are mentioned inuseStateMachine
's Wiki page XState comparison. - There's also
@xstate/fsm
, a 1 kB implementation of XState. Some differences are mentioned inuseStateMachine
's issue #27.
Two more good videos by Cassio on the topic:
- Custom State Machine Hook with useReducer & useEffect (28:36)
goes through implementing
useStateMachine
from scratch. The latest version of the library is a bit more robust (and also a bit more cryptic since it's written in fancy TypeScript). - React useStateMachine hook (18:17)
shows two examples
how to use the
useStateMachine
hook.