Finite State Machines

How to model application flows in React with finite state machines and XState

Application state in front-end clients is a complexity that is at best managed, and at worst the reason you can't deliver new features.

There are many ways to handle application state in modern front-end applications. You may be familiar with React's useState/useReducer hooks, Redux or one of the many other state management libraries. But, when you pair that state with business logic, a finite state machine can be a much better way to manage it.

Finite state what?

A finite state machine is a mathematical model of computation. It is an abstract "machine" that can be in exactly one of a finite number of states at any given time. The machine can transition from one state to another in response to some inputs known as events.

You define a finite state machine by a list of its states, its initial state and the events that trigger each transition.

Key takeaways

  • We can define a number of states a machine can be in.
  • The machine can transition from one state to another given some triggered events.
  • The machine can be in exactly one state at a time.

What does this look like in a real-world application?

Let’s take a real-world made-up (😝) example. You’re building a profile page for your application.

When users use your application for the first time, they have a blank profile. As the user enters the profile page, you want the profile page to display the profile if the user has one. If they don’t have a profile, you want to provide them with a way to create one and save it. If they do have a profile, you also want to offer them way to edit and save their profile.

Instead of having that imperative business logic scattered around the code, we can define it in a flow chart that everyone from developers up to stakeholders can see and understand.

Flow chart

From the diagram we can see that there are 9 distinct states:

  • Loading - While the app is fetching the user profile from the server
  • Failure state - When any server communication fails
  • Profile Loaded state - When the server has responded from the request for a profile
  • No profile state - When the user has not yet set up a profile
  • Creating profile state - When a user is creating a profile
  • Saving created profile state - When saving a created profile
  • Show profile state - When there is a profile to display
  • Editing profile state - When a user is editing a profile
  • Saving edited profile state - When saving an edited profile

The lines and arrows show how we transition from state-to-state. Sometimes we transition directly, sometimes based on a condition we transition to one state or another.

XState

Now that we know all the states and how to transition between them, we can go ahead and create our state machine using XState.

XState is one of the most comprehensive Javascript finite state machine libraries with additional tooling like visualisations.

We'll start by creating an XState machine using createMachine. We'll give it an id and an initial state which we'll say is loading, and we'll add a null value for profile and error to the context which you can think of as similar to React's state objects. We'll also list out all of the possible states.

js
1
import { assign, createMachine } from 'xstate';
2
3
const fetchMachine = createMachine({
4
id: 'Profile Page',
5
initial: 'loading', // initial state of our machine
6
context: {
7
profile: null,
8
error: null,
9
},
10
states: {
11
loading: {},
12
failure: {},
13
profileLoaded: {},
14
noProfile: {},
15
creatingProfile: {},
16
savingCreatedProfile: {},
17
showProfile: {},
18
editingProfile: {},
19
savingEditedProfile: {}
20
}
21
});
22

This yields a diagram of unconnected nodes.

Unconnected Nodes

Next, let's start filling out the loading state's details.

We'll add an invoke property which points to a fetchProfile service which is defined in the second parameter of the createMachine call. This means that when the machine is in the loading state, it will call the function defined in the fetchProfile service. This is an API call which returns a promise and some data.

We've defined onDone and onError properties on the loading state invoke property. These are invoked when the promise resolves or rejects.

If we get a successful response, we trigger XState's assign action to update the context with the event data then move on to the profileLoaded state.

Similarly, if we get an unsuccessful response, we'll transition to the failure state.

js
1
import { assign, createMachine } from 'xstate';
2
3
const fetchMachine = createMachine({
4
id: 'Profile Page',
5
initial: 'loading',
6
context: {
7
profile: null,
8
error: null
9
},
10
states: {
11
loading: {
12
invoke: {
13
/*
14
* The `fetchProfile` service is defined
15
* below in the services object
16
*/
17
src: 'fetchProfile',
18
onDone: {
19
target: "profileLoaded",
20
actions: assign({
21
// update `context.profile`
22
profile: (context, event) => event.data
23
24
})
25
},
26
onError: {
27
target: "failure",
28
actions: assign({
29
// update `context.error`
30
error: (context, event) => event.data
31
32
})
33
}
34
}
35
},
36
profileLoaded: {},
37
failure: {},
38
noProfile: {},
39
creatingProfile: {},
40
savingCreatedProfile: {},
41
showProfile: {},
42
editingProfile: {},
43
savingEditedProfile: {}
44
}
45
}, {
46
services: {
47
fetchProfile: Api.fetchProfile
48
}
49
});
50

Our state chart now looks like this.

Nodes with loading state

Next, let's add a guard called hasProfile into the second param passed to the createMachine object. This will return a boolean if the profile exists.

We'll also set up the profileLoaded state to check if the profile exists. If it does, move to the showProfile state, and if it doesn't, move to the noProfile state.

We use the "eventless" always property here to automatically move to the next state based on the guards.

js
1
import { assign, createMachine } from 'xstate';
2
3
const fetchMachine = createMachine({
4
id: 'Profile Page',
5
initial: 'loading',
6
context: {
7
profile: null,
8
error: null
9
},
10
states: {
11
loading: {
12
invoke: {
13
src: 'fetchProfile',
14
onDone: {
15
target: "profileLoaded",
16
actions: assign({
17
// update `context.profile`
18
profile: (context, event) => event.data
19
20
}),
21
},
22
onError: {
23
target: "failure",
24
actions: assign({
25
// update `context.error`
26
error: (context, event) => event.data
27
28
}),
29
},
30
}
31
32
},
33
profileLoaded: {
34
/*
35
* Eventless transitions - `always`
36
* They are invoked automatically when the parent's state
37
* is active.
38
*
39
* The condition `cond: 'hasProfile'` is defined in the guards
40
* object below. It checks if a profile exists in the context.
41
* If true, this transition occurs, if not the next one is attempted.
42
*/
43
always: [
44
{target: "showProfile", cond: "hasProfile"},
45
{target: "noProfile"},
46
],
47
},
48
failure: {},
49
noProfile: {},
50
creatingProfile: {},
51
savingCreatedProfile: {},
52
showProfile: {},
53
editingProfile: {},
54
savingEditedProfile: {}
55
}
56
}, {
57
services: {
58
fetchProfile: Api.fetchProfile
59
},
60
guards: {
61
hasProfile: (context) => !!context.profile
62
}
63
});
64

Our state chart now looks like this:

Nodes with profile loaded state

We're now going to add events and transitions for the noProfile and subsequent states.

We've added a CREATE_NEW_PROFILE event on the noProfile state which when triggered, will transition the state to the creatingProfile state.

We've also added events on the creatingProfile state to handle saving and cancelling the created profile.

js
1
import { assign, createMachine } from 'xstate';
2
3
const fetchMachine = createMachine({
4
id: 'Profile Page',
5
initial: 'loading',
6
context: {
7
profile: null,
8
error: null
9
},
10
states: {
11
loading: {
12
invoke: {
13
src: 'fetchProfile',
14
onDone: {
15
target: "profileLoaded",
16
actions: assign({
17
profile: (context, event) => event.data
18
19
}),
20
},
21
onError: {
22
target: "failure",
23
actions: assign({
24
error: (context, event) => event.data
25
26
}),
27
},
28
}
29
},
30
profileLoaded: {
31
always: [
32
{target: "showProfile", cond: "hasProfile"},
33
{target: "noProfile"},
34
],
35
},
36
failure: {},
37
noProfile: {
38
on: {
39
// User triggered event and the next state it targets
40
CREATE_NEW_PROFILE: 'creatingProfile'
41
}
42
},
43
creatingProfile: {
44
on: {
45
// User triggered events
46
SAVE_CREATED_PROFILE: 'savingCreatedProfile',
47
CANCELLED_SAVED_PROFILE: 'noProfile'
48
}
49
},
50
savingCreatedProfile: {},
51
showProfile: {},
52
editingProfile: {},
53
savingEditedProfile: {}
54
}
55
}, {
56
services: {
57
fetchProfile: Api.fetchProfile
58
},
59
guards: {
60
hasProfile: (context) => !!context.profile
61
}
62
});
63

Our state diagram now looks like this:

Nodes with creating profile state

Putting it all together

Finally, we'll fill out the rest of the states, transitions and services based on what we know from the previous steps to end up with this:

js
1
import { assign, createMachine } from 'xstate';
2
3
const fetchMachine = createMachine({
4
id: 'Profile Page',
5
initial: 'loading',
6
context: {
7
profile: null,
8
error: null
9
},
10
states: {
11
loading: {
12
invoke: {
13
src: 'fetchProfile',
14
onDone: {
15
target: "profileLoaded",
16
actions: assign({
17
profile: (context, event) => event.data
18
19
}),
20
},
21
onError: {
22
target: "failure",
23
actions: assign({
24
error: (context, event) => event.data
25
26
}),
27
},
28
}
29
30
},
31
profileLoaded: {
32
always: [
33
{target: "showProfile", cond: "hasProfile"},
34
{target: "noProfile"},
35
]
36
},
37
noProfile: {
38
on: {
39
CREATE_NEW_PROFILE: 'creatingProfile'
40
}
41
},
42
creatingProfile: {
43
on: {
44
SAVE_CREATED_PROFILE: 'savingCreatedProfile',
45
CANCEL_SAVED_PROFILE: 'noProfile'
46
}
47
},
48
savingCreatedProfile: {
49
invoke: {
50
src: 'saveProfile',
51
onDone: 'loading',
52
onError: 'failure'
53
}
54
},
55
showProfile: {
56
on: {
57
EDIT_PROFILE: 'editingProfile'
58
}
59
},
60
editingProfile: {
61
on: {
62
SAVE_EDITED_PROFILE: 'savingEditedProfile',
63
CANCEL_EDITED_PROFILE: 'showProfile'
64
}
65
},
66
savingEditedProfile: {
67
invoke: {
68
src: 'saveProfile',
69
onDone: 'loading',
70
onError: 'failure'
71
}
72
},
73
failure: {},
74
}
75
}, {
76
services: {
77
fetchProfile: Api.fetchProfile,
78
saveProfile: Api.saveProfile,
79
},
80
guards: {
81
hasProfile: (context) => !!context.profile
82
}
83
});
84

Our final state diagram might look a little busy due to the layout, but it has equivalent steps to our original flow chart above.

This diagram represents the business logic that is often ill-defined and scattered throughout your code. The advantage of using a FSM is that we have to think about this state upfront, so we can understand and define it better.

That alone can reduce bugs and miscommunication during the build process, maintenance and additional feature building.

Final state chart

XState React

Now to use this in React, we simply add the @xstate/react package and import the useMachine hook

jsx
1
const ProfilePage = () => {
2
const [state, send] = useMachine(machine);
3
4
if(state.matches('loading')) {
5
return <LoadingSpinner />
6
}
7
8
if(state.matches('error')) {
9
return <ErrorMessage error={state.context.error}/>
10
}
11
12
if(state.matches('noProfile')) {
13
return <CreateProfileNudge onCreateClick={() => send('CREATE_NEW_PROFILE')}/>
14
}
15
16
if(state.matches('showProfile')) {
17
return <ProfileContent profile={state.context.profile} />
18
}
19
/* ... */
20
}
21

state is an object that has value (the current machine state) and context (the object with our profile and error).

There is also a matches function on the state object that can be used to match states.

We can send state appropriate events to the machine via the send function. For example, when in the showProfile state, we can call send('EDIT_PROFILE') and the state will transition from showProfile to editingProfile.

When changes to the state object occur, the component will re-render allowing you to respond to those state changes with appropriate UI code.

The wash up

Finite State Machines are a pretty nice way to force you to think about the states your application could be in upfront, then encode those states into a machine which drives your user-experience.

We often deal with this complexity in React using multiple useState or useReducer hooks or global state management solutions. This approach doesn't need to replace them, but it provides a useful tool in your toolbox to control some of the more complex workflows that you might come up against from time to time.

Go forth and be state machined!