Course contentsShow
← React
Lesson 1755 of 2,39641. State Management EcosystemFree lesson

Actions: Side Effects on Transitions

Executing logic during transitions with entry/exit actions and transition actions.

Actions: Side Effects on Transitions

You'll learn how to execute side effect logic automatically whenever your state machine transitions between states.

The Core Idea

While context holds your extended state data, actions let you run side effects when transitions happen. Think of actions as the "do this when..." instructions in your machine. They're perfect for logging, API calls, updating external systems, or any imperative code that should fire during a state change.

Actions come in three flavors:

Entry Actions

Run when entering a state:

const machine = createMachine({
  states: {
    loading: {
      entry: 'fetchData' // runs when entering 'loading'
    }
  }
});

Exit Actions

Run when leaving a state:

const machine = createMachine({
  states: {
    editing: {
      exit: 'saveToLocalStorage' // runs when leaving 'editing'
    }
  }
});

Transition Actions

Run during the transition itself:

const machine = createMachine({
  states: {
    idle: {
      on: {
        SUBMIT: {
          target: 'loading',
          actions: 'logSubmission' // runs during transition
        }
      }
    }
  }
});

Implementing Actions

You define the actual functions in the second argument to createMachine:

const machine = createMachine({
  // machine config...
}, {
  actions: {
    fetchData: () => console.log('Fetching...'),
    logSubmission: (context, event) => {
      console.log('User submitted:', event.payload);
    }
  }
});

Actions receive context and the triggering event, letting them respond to both current state data and incoming information.

Key Takeaway: Actions let you declaratively attach side effects to state transitions—enter a state, run this; leave a state, run that; transition happens, execute logic. This keeps your state machine pure while handling real-world imperative needs.