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 1 reply
-
|
Before providing a detailed answer, would it be possible to migrate to XState v5? |
Beta Was this translation helpful? Give feedback.
1 reply
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
useMemoto memoize andinterpret(...).start()directly:Possible Pros:
Possible Cons:
interpreteris created during render, which might go against React best practices?Here, I use useInterpret from
@xstate/react, and rely onkeyat the component level to force remounting the provider:Possible Pros:
useInterpretstarts the service in a React-safe way (in anuseEffect)?keychanges - no manual stop needed?Possible Cons:
keyimplementation)Why I moved away from useInterpret initially
I initially used
useInterpretdirectly, but found that it does not recreate theinterpreterwhen 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
interpretdirectly insideuseMemo- until I realised that doing so might introduce render-phase side effects and potential memory leaks.❓ My Questions
useInterpret+keythe 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