Adding Side Effects and Actions
You'll learn how to execute functions during state machine transitions to perform useful work like logging, API calls, or updating the UI.
The Core Idea
A finite-state machine isn't just about moving between states—it's about doing things when those transitions happen. Actions (also called side effects) are functions that run:
- On entry: when entering a new state
- On exit: when leaving a state
- During transition: while moving from one state to another
Think of it like a hotel room: when you check in (entry), staff might turn on the lights and air conditioning. While you're staying (state), nothing automatic happens. When you check out (exit), they clean the room and update the booking system.
Adding Actions to Your FSM
You can enhance your state machine object to include action functions:
const trafficLight = {
currentState: 'green',
states: {
green: {
onEntry: () => console.log('Green light ON'),
onExit: () => console.log('Green light OFF'),
transitions: { TIMER: 'yellow' }
},
yellow: {
onEntry: () => console.log('Yellow light ON'),
onExit: () => console.log('Yellow light OFF'),
transitions: { TIMER: 'red' }
},
red: {
onEntry: () => console.log('Red light ON'),
onExit: () => console.log('Red light OFF'),
transitions: { TIMER: 'green' }
}
}
};
Your transition function now triggers these actions:
function transition(machine, event) {
const state = machine.states[machine.currentState];
const nextState = state.transitions[event];
if (nextState) {
state.onExit?.(); // Call exit action if it exists
machine.currentState = nextState;
machine.states[nextState].onEntry?.(); // Call entry action
}
}
transition(trafficLight, 'TIMER');
// Logs: "Green light OFF" then "Yellow light ON"
Key Takeaway: Side effects and actions turn state machines from abstract models into practical tools that perform real work during state changes, making your application logic both organized and observable.