DEV Community

Cover image for XState: What's the difference between Machine and createMachine?
Matt Pocock
Matt Pocock

Posted on

8 1

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 });
Enter fullscreen mode Exit fullscreen mode

...or...

import { createMachine } from 'xstate';

const machine = createMachine({ ...config });
Enter fullscreen mode Exit fullscreen mode

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 });
Enter fullscreen mode Exit fullscreen mode

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 });
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay