The Machine Object
Implementing the machine is only half the fun. Let's look at how to use the machine in your React components.
The useMachine
hook returns an object with all the stuff you need to work with your machine:
- the current state (and various ways to match it)
- the current context
- pre-bound event dispatchers
#
Dispatching eventsDispatching events is a bit different in Fini, compared to how it works with useReducer
, Redux
and XState
. Instead of using a dispatch
function to dispatch action/event objects, the object returned from useMachine
provides event functions that are pre-bound to Fini's internal dispatch function. This means dispatching events becomes as easy as this:
This is so you won't have to either create action creators or manually write dispatch({ type: "increment" })
(this is what happens internally, though!).
#
Inspecting the stateAs mentioned, the machine
object also contains everything you need to know about the current state of the machine.
To examine its properties, it's easiest with an example.
Ignoring event dispatching functions, console.log(counterMachine)
will output
If we were to run counterMachine.start()
, machine
would look like this:
This example also has a state-specific context, i.e. { count: 0 }
. Since Fini tries to protect you from run-time errors, you cannot access counterMachine.context.count
without first checking that you're in the counting
state:
Meanwhile, counterMachine.context.maxCount
is "globally" defined, and is accessible in all states.
Finally, these state matchers are also very handy when determining what parts of our UI we should render: