Context: Extended State in Machines
What you'll learn: How to store additional data alongside your finite states in XState machines, and how to update that data when events occur.
Beyond Just States
A state machine tells you which state you're in (like "idle" or "loading"), but real apps need more than that — they need data. What are you loading? What error message occurred? How many times has something happened?
Context is XState's solution: an object that lives inside your machine, traveling alongside your finite states. Think of it as the machine's memory or backpack — it carries extra information that doesn't fit neatly into a state name.
Defining and Using Context
When you create a machine, add a context property with your initial data:
import { createMachine } from 'xstate';
const counterMachine = createMachine({
context: {
count: 0,
lastUpdated: null
},
initial: 'active',
states: {
active: {
on: {
INCREMENT: {
actions: 'incrementCount'
}
}
}
}
});
Updating Context with assign
Use the assign action to update context when transitions happen:
import { createMachine, assign } from 'xstate';
const counterMachine = createMachine({
context: { count: 0 },
initial: 'active',
states: {
active: {
on: {
INCREMENT: {
actions: assign({
count: (context) => context.count + 1
})
}
}
}
}
});
The assign function merges your updates into the existing context. Access the updated context through useMachine's returned state: state.context.count.
Key Takeaway: Context lets your state machines remember data beyond just "which state am I in," and assign actions update that data immutably during transitions.