What State Machines Are and Why We Use Them

How can we «run» the state machine and ensure that our program is deterministic, as the mathematical concept promises?The answer is XState.

XState is a fantastic JavaScript and TypeScript implementation of finite state machines by David Khourshid.

With the above code block as a configuration, a state machine can be instantiated and will adhere to the given rules.

import { Machine } from 'xstate';const bookMachine = Machine({ "initial": "In Stock", "states": { "In Stock": { on: { "Lend": "Lent", }, }, "Lent": { on: { "Return": "In Stock", "Damage": "Damaged", "Lose": "Lost", }, }, "Damaged": { on: { "Repair": "In Stock", }, }, "Lost": { on: { "Find": "In Stock", }, }, }});After the instantiation the state machine will be in the initial state: In Stock.

Sending an input from the alphabet ????.will either result in a state transition or do nothing; for example if the state machine is in the initial state and receives a Lend action, the following state will be Lent.

If it’s any other input, the state will remain the same.

Implementing our UI-heavy apps with state machines has helped us immensely to reduce complexity.

As our applications grew (and still do!), state diagrams also facilitate the entry for new developers on these projects massively in understanding what is going on, and also get a grasp of what the applications include apart from the “obvious” features.

But obviously you want hard facts.

You want examples and see real scenarios how we use state machines in apps.

And that’s exactly what the next post will be about — how we integrate state machines in our React apps, how we connect state transitions to our components and how we render based on what state our state machine currently is in.

A thousand thanks and credits go to David Khourshid for writing XState — an incredible library which is a charm to use.

David constantly delivers updates to the code and documentation, and an awesome developer experience by supporting devtools like redux-devtools.

Make sure you read his posts for more insights.

The FaceTime Bug and the Dangers of Implicit State MachinesFaceTime hit a pretty serious bug.

Apparently, if you start a FaceTime video call, swipe up, tap “Add Person” before…medium.

comNeed an expert team to implement your advanced web application?.Check out smartive’s portfolio.

At smartive, we build web applications for complex use cases.

We are located in Zurich, Switzerland.

.. More details

Leave a Reply