{"id":18023,"library":"zustand-middleware-xstate","title":"Zustand XState Middleware","description":"Zustand middleware for integrating XState state machines into a global Zustand store. Currently at version 3.0.1, this package is designed to work seamlessly with XState v5 and Zustand v4, ensuring compatibility with their latest APIs and features. It provides a straightforward mechanism to create a Zustand store from an XState machine, exposing the machine's current `state`, the `send` event function, and the underlying `actor` for component consumption. This enables developers to leverage Zustand's reactive state management and selector capabilities to optimize re-renders while benefiting from XState's robust state orchestration. The middleware also allows passing actor options, such as `devTools`, directly to the XState actor, enhancing debugging and development workflows. While specific release cadences aren't explicitly stated, its alignment with major versions of its peer dependencies suggests active maintenance in response to their evolution.","status":"active","version":"3.0.1","language":"javascript","source_language":"en","source_url":"https://github.com/biowaffeln/zustand-middleware-xstate","tags":["javascript","typescript"],"install":[{"cmd":"npm install zustand-middleware-xstate","lang":"bash","label":"npm"},{"cmd":"yarn add zustand-middleware-xstate","lang":"bash","label":"yarn"},{"cmd":"pnpm add zustand-middleware-xstate","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Peer dependency required for state machine logic (v5+).","package":"xstate","optional":false},{"reason":"Peer dependency required for state management (v4+).","package":"zustand","optional":false}],"imports":[{"note":"Zustand v4+ exports `create` as a default export. Using named import will result in `undefined`.","wrong":"import { create } from 'zustand'","symbol":"create","correct":"import create from 'zustand'"},{"note":"XState v5 exports `setup` as a named export. It's crucial for defining machine types and configurations in v5.","wrong":"import setup from 'xstate'","symbol":"setup","correct":"import { setup } from 'xstate'"},{"note":"The middleware function `xstate` is the default export from this package.","wrong":"import { xstate } from 'zustand-middleware-xstate'","symbol":"xstate","correct":"import xstate from 'zustand-middleware-xstate'"}],"quickstart":{"code":"import create from \"zustand\";\nimport { setup } from \"xstate\";\nimport xstate from \"zustand-middleware-xstate\";\n\ntype UserEvents = { type: 'LOGIN' } | { type: 'LOGOUT' };\n\n// Create your XState machine definition using setup\nconst authMachine = setup({\n  types: {\n    events: {} as UserEvents,\n    context: {} as { userId: string | null }\n  },\n}).createMachine({\n  id: \"auth\",\n  initial: \"loggedOut\",\n  context: { userId: null },\n  states: {\n    loggedOut: {\n      on: {\n        LOGIN: {\n          target: \"loggedIn\",\n          actions: ({ context }) => {\n            // In a real app, you'd set the actual user ID\n            context.userId = 'some-user-id-' + Math.random().toFixed(2);\n          }\n        }\n      }\n    },\n    loggedIn: {\n      on: {\n        LOGOUT: {\n          target: \"loggedOut\",\n          actions: ({ context }) => {\n            context.userId = null;\n          }\n        }\n      }\n    }\n  }\n});\n\n// Create a Zustand store hook using the xstate middleware\nconst useAuthStore = create(\n  xstate(authMachine, { devTools: process.env.NODE_ENV === 'development' })\n);\n\n// Example usage in a component-like structure\nconst AuthComponent = () => {\n  const { state, send, actor } = useAuthStore();\n\n  console.log('Current Auth State:', state.value);\n  console.log('User ID:', state.context.userId);\n\n  return (\n    <div>\n      <p>Authentication Status: {String(state.value)}</p>\n      {state.matches('loggedOut') && (\n        <button onClick={() => send({ type: 'LOGIN' })}>Login</button>\n      )}\n      {state.matches('loggedIn') && (\n        <button onClick={() => send({ type: 'LOGOUT' })}>Logout</button>\n      )}\n      <p>Actor status: {actor.getSnapshot().status}</p>\n    </div>\n  );\n};\n\n// Simulate rendering\nAuthComponent(); // Initial render\nuseAuthStore.getState().send({ type: 'LOGIN' }); // Simulate user login\nAuthComponent(); // Re-render after login\nuseAuthStore.getState().send({ type: 'LOGOUT' }); // Simulate user logout\nAuthComponent(); // Re-render after logout","lang":"typescript","description":"Demonstrates creating an XState machine, integrating it into a Zustand store with the middleware, and accessing state and send function."},"warnings":[{"fix":"Ensure your project uses `xstate@^5.15.0` and `zustand@^4.1.4` (or compatible versions) by upgrading your `package.json` dependencies and running `npm install`.","message":"This middleware requires XState v5+ and Zustand v4+ as peer dependencies. Older versions of XState (e.g., v4) are not compatible due to significant API changes in XState v5, particularly around machine creation and actor management.","severity":"breaking","affected_versions":"<3.0.0"},{"fix":"Refactor your XState machine definitions to use `setup({ ... }).createMachine({ ... })` as shown in the XState v5 documentation and the quickstart example.","message":"When migrating from XState v4, remember that XState v5 introduces the `setup` API for machine definition. Directly passing old XState v4 machine definition objects will lead to runtime errors.","severity":"gotcha","affected_versions":">=3.0.0"},{"fix":"Use `import create from 'zustand'` instead of `import { create } from 'zustand'` for Zustand v4 and newer.","message":"The `create` function from `zustand` is a default export in v4+, not a named export. Incorrect import syntax will cause runtime errors.","severity":"gotcha","affected_versions":">=3.0.0"},{"fix":"Always pass the result of `setup({ ... }).createMachine({ ... })` to the `xstate` middleware function.","message":"The `xstate` middleware expects an already created XState machine instance (the return value of `setup(...).createMachine(...)`), not just a plain machine configuration object.","severity":"gotcha","affected_versions":">=3.0.0"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"fix":"Change `import { create } from 'zustand'` to `import create from 'zustand'`.","cause":"Attempting to import `create` from 'zustand' as a named export when it is a default export in Zustand v4+.","error":"TypeError: create is not a function"},{"fix":"Ensure your XState machine is created using `const machine = setup({ ... }).createMachine({ ... });` before passing `machine` to `xstate(machine)`.","cause":"Passing an XState v4 machine definition or an incorrectly structured object to the middleware, which expects an XState v5 machine created with `setup().createMachine()`.","error":"TypeError: machine.createMachine is not a function"},{"fix":"Verify that `xstate` (v5+) and `zustand` (v4+) are correctly installed and that the machine passed to the middleware is a valid XState v5 machine instance. Check console for earlier initialization errors.","cause":"This usually indicates the XState machine or the Zustand store was not correctly initialized, or a peer dependency (XState/Zustand) version mismatch is preventing the middleware from creating a valid machine instance.","error":"TypeError: Cannot read properties of undefined (reading 'value') when accessing state.value"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}