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.
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.
Top comments (1)
👍