An Interest In:
Web News this Week
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
- March 27, 2024
- March 26, 2024
XState: What's the difference between Machine and createMachine?
XState offers two options for declaring machine definitions:
import { Machine } from 'xstate';const machine = Machine({ ...config });
...or...
import { createMachine } from 'xstate';const machine = createMachine({ ...config });
This can be confusing for beginners. Why are there two very similar-looking methods? What's the difference?
The Difference
In Javascript, there is no difference between the two. You can use them completely interchangeably.
In Typescript, there is only a small difference between them - it's to do with the ordering of the generics you can pass to the machine. Machine
allows you to pass a generic called 'Typestates' in the middle of the Context
and Event
generics.
import { Machine } from 'xstate';interface Context {}type Event = { type: 'EVENT_NAME' }type States = {}const machine = Machine<Context, States, Event>({ ...config });
Whereas createMachine
asks you to insert it at the end:
import { createMachine } from 'xstate';interface Context {}type Event = { type: 'EVENT_NAME' }type States = {}const machine = createMachine<Context, Event, States>({ ...config });
Whichever you choose, there is no functional difference in the created machine. The two functions reference the same code, and create the machine in the same way.
What should I choose?
Going forward, you should use createMachine
. That's the syntax that will be preferred when v5 releases. But if you're happy with Machine, you can keep using it.
Original Link: https://dev.to/mpocock1/xstate-what-s-the-difference-between-machine-and-createmachine-15h1
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To