Advanced State Management – XState

Here, we will use and discuss about XState which is a state management and orchestration solution for both JavaScript and TypeScript apps for both frontend and backend applications.

For bigger applications managing the global state properly is essenti…


This content originally appeared on DEV Community and was authored by Shagun Bidawatka

Here, we will use and discuss about XState which is a state management and orchestration solution for both JavaScript and TypeScript apps for both frontend and backend applications.

For bigger applications managing the global state properly is essential, there are several ways to do so, like using React context, Redux, MobX and React Query.

XState is a simple library to manage state component level as well as global level by using their hooks. So, let's dive into it's implementation.

1. Import the module

We will be importing both xstate and @xstate/react latest versions into our existing project.

npm install xstate @xstate/react

2. Adding machine

Create a new file eg: MyFirstMachine.ts

const countMachine = createMachine({
  context: {
    count: 0,
  },
  on: {
    INC: {
      actions: assign({
        count: ({ context }) => context.count + 1,
      }),
    },
    DEC: {
      actions: assign({
        count: ({ context }) => context.count - 1,
      }),
    },
    SET: {
      actions: assign({
        count: ({ event }) => event.value,
      }),
    },
  },
});

You can see the visualisation of the machine using Xstate Vscode extension.

Machine visualization

3. Using machine and create actor

To use the global logic we have implemented in our machine. We will use two hooks useMachine and createActor.

 const [state, send] = useMachine(countMachine);
 const countActor = createActor(countMachine).start();

4. Performing actions

Now, can perform read and write actions using these constants.
To modify the value use -

send({ type: "INC" })
send({ type: "DEC" })
send({ type: "SET", value: 5 })

And the access the updated real-time value we will value use-

state.context

Adding complete code file for accessing and modifying for your convenience.

import { useMachine } from "@xstate/react";
import { countMachine } from "./XstateMachine";
import { createActor } from "xstate";

const App = () => {
  const [state, send] = useMachine(countMachine);
  const countActor = createActor(countMachine).start();

  countActor.subscribe((state) => {
    console.log(state.context.count);
  });

  return (
      <div className="relative z-0 bg-primary text-center">
        <div>Hello XSTATE</div>
        <div>{JSON.stringify(state.context)}</div>

        <button onClick={() => send({ type: "INC" })}>Increase By 1</button>

        <button onClick={() => send({ type: "DEC" })}>Decrease By 1</button>

        <button onClick={() => send({ type: "SET", value: 5 })}>
          Set Count to 5
        </button>
      </div>
  );
};

export default App;

That's how you can read, write and modify the state just by using XState. I have used multiple state management ways, it is one of the simplest ways I found. If you have anything to add to it feel free to comment.


This content originally appeared on DEV Community and was authored by Shagun Bidawatka


Print Share Comment Cite Upload Translate Updates
APA

Shagun Bidawatka | Sciencx (2024-07-21T11:30:06+00:00) Advanced State Management – XState. Retrieved from https://www.scien.cx/2024/07/21/advanced-state-management-xstate/

MLA
" » Advanced State Management – XState." Shagun Bidawatka | Sciencx - Sunday July 21, 2024, https://www.scien.cx/2024/07/21/advanced-state-management-xstate/
HARVARD
Shagun Bidawatka | Sciencx Sunday July 21, 2024 » Advanced State Management – XState., viewed ,<https://www.scien.cx/2024/07/21/advanced-state-management-xstate/>
VANCOUVER
Shagun Bidawatka | Sciencx - » Advanced State Management – XState. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/07/21/advanced-state-management-xstate/
CHICAGO
" » Advanced State Management – XState." Shagun Bidawatka | Sciencx - Accessed . https://www.scien.cx/2024/07/21/advanced-state-management-xstate/
IEEE
" » Advanced State Management – XState." Shagun Bidawatka | Sciencx [Online]. Available: https://www.scien.cx/2024/07/21/advanced-state-management-xstate/. [Accessed: ]
rf:citation
» Advanced State Management – XState | Shagun Bidawatka | Sciencx | https://www.scien.cx/2024/07/21/advanced-state-management-xstate/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.