What is the recommended way to provide an XState machine instance that depends on external props? #5346
Unanswered
inakiarroyo
asked this question in
Q&A
Replies: 1 comment
-
Before providing a detailed answer, would it be possible to migrate to XState v5? |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Hi everyone 👋
I'm working on integrating an XState machine (
tagMachine
) into a React project and want to clarify the best approach for initialising and providing an interpreter instance based on external props (e.g.,tags
,isNote
,onTagsUpdate
). My goal is to keep the interpreter:Ensure a stable machine instance
We want the machine to remain stable between renders, unless a meaningful prop change requires resetting the machine (e.g., switching from "
note
" to "message
" mode)Here I use
useMemo
to memoize andinterpret(...).start()
directly:Possible Pros:
Possible Cons:
interpreter
is created during render, which might go against React best practices?Here, I use useInterpret from
@xstate/react
, and rely onkey
at the component level to force remounting the provider:Possible Pros:
useInterpret
starts the service in a React-safe way (in anuseEffect
)?key
changes - no manual stop needed?Possible Cons:
key
implementation)Why I moved away from useInterpret initially
I initially used
useInterpret
directly, but found that it does not recreate theinterpreter
when the machine config/context changes. The interpreter remained the same across renders. This meantselectedTags
,entryType
, etc., were only set on initial mount, unless I manually sent sync events.This led me to consider using
interpret
directly insideuseMemo
- until I realised that doing so might introduce render-phase side effects and potential memory leaks.❓ My Questions
useInterpret
+key
the recommended way to safely recreate interpreters with new context/config?Any thoughts, insights, or best practices would be super appreciated 🙏
Thanks in advance!
Beta Was this translation helpful? Give feedback.
All reactions