Looking at the example above, you may be thinking; what’s the point of using a state machine? It seems like we’re needlessly adding a layer of complexity to a simple feature that most web applications built today support happily without a state machine.
Here’s a secret. All software development is building state machines.
Computers are themselves FSMs. As is all the software we write on top of them. It’s just that we don’t normally think of the enormous space of possible states, instead we think in terms of values of variables and what they represent in our software.
Thinking explicitly in terms of FSMs for small parts of our software makes it easy to reason about it, which is why it’s very useful to model our software as an FSM on smaller scales, in critical modules where we must be absolutely sure of how the software will react to different inputs.
I think this whole state machine business is a lot easier to explain with a code sample. Xstate is a popular JS library that makes it easy to build state machines. Instead of copying the code here, I’ll just link it.
Here’s a tutorial from the Xstate site that walks you through building an app that displays post from a sub-Reddit. Notice how the code is simpler to reason about. You’re almost breaking the functionality into it’s constituent pieces; what to do while the posts are loading, what behavior to expose when the posts are loaded, and how to react if loading fails.