Check out a free preview of the full State Modeling in React with XState course:
The "Extended State" Lesson is part of the full, State Modeling in React with XState course featured in this preview video. Here's what you'd learn in this lesson:

David explains that extended state properties are state properties without finite values. They are stored in a context object within the state machine.

Get Unlimited Access Now

Transcript from the "Extended State" Lesson

[00:00:01]
>> All right, so let's go over how we could show both finite state and coil unquote, infinite state or extended data as well. Let's say in this alarm machine, we want to keep track of how many times we clicked the toggle button. To go from pending, sorry, from inactive to pending.

[00:00:28] So let's just keep accounts there. We're going to be using the context property on create machines to keep track of this extended States. So we'll have count and started at zero. Now this context is available on the state dot context property. So we could say const count equals state context dot counts.

[00:00:52] Could actually make this shorter and just use ES6 destructuring to grab that counts from state context. And so now let's put that in here. And so we could see that extended state value, which, again, is data that doesn't necessarily fit in finite states. It could potentially be infinite.

[00:01:16] If you click this button an infinite amount of times. That is expressed through state context. Now in order to change this context, we could use an action. And x state has a built in assign action. And it's important to note that the assign action is a pure function.

[00:01:35] All it does is return an object. So if we do console dot log A sign counts 100. We're going to get an object that has an assignment's property of counts a hundred. And it's not actually going to magically do any assignments itself. The way we actually had that action, change the context is by doing it in actions.

[00:02:02] So, for example, in this toggle transition, you could specify that one of the actions. Should be assigning the counts to 100. So, see what happens there. If we click here, it will change to 100. Now obviously, we don't want it to change to a static value in this case, we want to keep track based on the previous count.

[00:02:29] How many times that button has been clicked. And so we can do that by passing in a function that takes two arguments, the context hence the events. Which is the events object that caused this transition to happen. So we could say that this count should be the context that counts which is the previous count + 1.

[00:02:52] So now, every time we click this pending button, so click here. And then, so every time it's white, and we click it. This counts will increments and that's how we could represent extended states within our state machines.