Simplifying complicated

After reading this article you will learn one of the ways to make programming a little bit saner using XState.

Example

Let's see what a state machine looks like by creating a light switch. It can be switchedOff or switchedOn. At each position, you can SWITCH. Let's describe it in some sort of a structure:
1{
2 "states": {
3 "switchedOff": {
4 "on": {
5 "SWITCH": "switchedOn"
6 }
7 },
8 "switchedOn": {
9 "on": {
10 "SWITCH": "switchedOff"
11 }
12 }
13 },
14
15 "initial": "switchedOff",
16 "id": "light"
17}

Top-down style

What I like about this approach is that you need to think about the app first and then develop it. The same goes for when you need to make a new feature – the developer has to think about how it fits in the current machine.
You are thinking about the app at a very high abstraction level without sinking into the details. You need to think of states that a form can be: loading, submitting, error; as opposed to how to vertically center the submit button using CSS. This results in better architecture which leads to great UX.

Easier refactoring

I'm able to drastically move stuff around without breaking the app. This makes me braver to make a change because I know that it will work in the end.
This comes from the fact that you have thought about the app states and you already have some of the parts working. Having a state machine is like a proven theorem: you know it works, and just need to polish out some of the details to make it work in practice.

Fewer bugs

XState removes a class of bugs since a state machine can be only in one state and that state can be transitioned by an only known list of events. This means no more buttons that are disabled and loading at the same time.

Tools

Good news – the structure I’ve shown you is actually standardized which means – great tools! One of the obvious ones is visualizing it:
But wait, there is more. Since we can visualize the state, the next obvious idea is to attach it to your current machine in the current UI in the browser and see how the state is changing. It's called Inspector.

Steep learning curve

You need to learn a lot of concepts and read a lot of code before you can start using XState effectively. And even after that, it will slow you down at times – kind of just like static typing.

Conclusion

I will be using XState where the UI is too complex and I need a robust solution. I hope I have convinced you to give it a try – go read the docs!