Skip to content
Discussion options

You must be logged in to vote

Hi! Yes, using a function for the context is the correct solution here. Let me explain why:

The Problem

Zag machines capture their context once during initialization. When you pass a static object to useMachine, the
machine takes a snapshot of those values and doesn't automatically react to prop changes.

The Solution

By passing a function that returns the context, you're enabling the machine to receive fresh values on each evaluation:

const service = useMachine(zagSwitch.machine, () => ({
  ...machineProps,
  value,
  checked,
  onCheckedChange(details) {
    checked = details.checked
    machineProps.onCheckedChange?.(details)
  },
}))

This works because:

  1. Reactive Context: The function …

Replies: 3 comments

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Answer selected by segunadebayo
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants