Use Internal Transitions in XState to Avoid State Exit and Re-Entry

Kyle Shevlin
InstructorKyle Shevlin
Share this video with your friends

Social Share Links

Send Tweet
Published 4 years ago
Updated 3 years ago

Transitions come in two varieties: "external" and "internal". By default, a transition is considered external. This means that a transition will exit the current state node, and enter the next state node (even if that state node is the state the machine is currently in). This exit/enter loop will trigger any actions that are set on the exit and entry properties.

A transition can be set to internal, either through setting a . (dot) in front of the state node name (as we do in this lesson), or through setting the property internal to true on the transition object.

When a transition is internal, it will not exit and enter the state node, which means that the actions in the exit/transition/entry loop will not be called.

Instructor: [00:00] Here I have a contrived example of a machine, an idle machine, that only has one state, idle. On this machine, we only have one event, do-nothing. It transitions back to the idle state. Let's give it a couple tries.

[00:15] We can see that each time we call do-nothing, we actually exit the idle state. We leave it, calling the log exit action, which is down here in logs exited, and then we reenter the idle state, calling the entry action log entry that logs entered. Hence why, exited-entered, exited-entered, exited-entered.

[00:38] Now, on occasion, you might want to transition back to the same state without ever leaving the state node, and thus, never reentering the state node. How do we do that in XState?

[00:50] Well, we can do it quite simply by adding one character. We add this period, this dot notation, and what we've told the machine is that we would like to make an internal transition.

[01:01] We want to make a transition that stays within the state it's in. We don't want to exit it and we don't want to enter it, so we're going to update our machine.

[01:09] Notice that the arrow slightly changed. If we call do-nothing now, we'll see that nothing gets logged out to the terminal. I hope you can hear me clicking.

[01:19] This simple change creates a transition where we never leave this node.

Patrik Affentranger
Patrik Affentranger
~ 4 years ago

Would be good to highlight the benefit or use case for internal transitions?

Ian Jones
Ian Jones
~ 4 years ago

I asked this on Twitter and David gave me this reply:

It's just another way of specifying exactly which actions you want to be executed for a transition. It's one of those things that you'll know when you need it.

In general, prefer transition actions instead of entry/exit if you're concerned.

Markdown supported.
Become a member to join the discussionEnroll Today