State Machines
As it turns out, this super old concept in Computer Science is fantastic for managing UI state.
Our libarary of choice is xstate for a few reasons:
- No dependencies
- Closely follows the SCXML Specification
- The visualizer is fantastic
- It works great and we haven't had to look for a different option
How State Machines works
The XState documentation great and is the best resource for up-to-date tutorials.
Why we use state machines for UI state
State machines are defined as a set of specific states and the transitions between them. This makes them an optimal choice for managing UI state.
Benefits:
- A documented set of UI states
- Specific transitions from one state to another
- Forces us to design with all states in mind as well as how to navigate them
- No more broken states leaving a customer stranded
- Emphasis on loading and error states
How we use them
As we've learned how to use state machines in a practical way, it has become clear that multiple smaller machines are favourable to larger ones.
Aside from the 2FA feature, which is the first feature done using XState, we typically define and use machines within context providers.
Current implementations of this pattern include:
- Authentication (user-provider.js)
- Payment Settings (credit-card-payment-provider.tsx)
- Google Workspace (google-workspace-provider.js)
By combining the use of small machines within the same context provider, we can keep the logic more concise. For example, CRUD operations would each have their own machines. The provider stitches these machines together and allows for added logic between machines. This is all absctracted away from any UI components using the context provider.