Using Shared Context
Retomus lets you create and consume shared global context across multiple machines and components.
This is useful for centralizing common state like user session, UI flags, or synced values.
🔧 Defining a Shared Context​
Use retomus.createCtx()
to define a named shared context:
const sharedCtx = retomus.createCtx('sharedCtx', {
state: {
count: 0,
user: null,
},
});
This context is now globally available via the ID 'sharedCtx'
.
📥 Accessing Shared Values​
From any component or machine, you can access context values:
const count = sharedCtx.useState('count');
const user = sharedCtx.useState('user');
These are fully reactive and will update your component when changed.
🧩 Integration With Machines​
Machines can read from or write to sharedCtx using the sharedCtxIds
option:
const machineConfig = createMachineConfig({
id: 'example',
status: ['idle'],
actions: ['update'],
actionHandlers: {
update: async ({ ctx, done }) => {
ctx.sharedCtx.state.count += 1;
done();
},
},
initialStatus: {
status: 'idle',
},
transitions: {},
ctx: {
state: {},
},
options: {
sharedCtxIds: ['sharedCtx'],
},
});
💡 When Should I Use Shared Context?​
Use Case | Example |
---|---|
Global counters or themes | ctx.sharedCtx.state.theme = 'dark' |
Cross-component coordination | Shared loading flags |
Session/user state | ctx.sharedCtx.state.user |
🧠Tips​
- Avoid overusing shared context — use it where true global state is needed.
- Keep sharedCtx schema minimal and focused.
- You can create multiple named contexts for separation of concerns.