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.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay