Function useSharedMachine

  • Uses a shared state machine.

    This hook allows a state machine to be shared between hooks or between hooks and external asynchronous events. You need to create a state machine specifically for this hook using createSharedMachine. The shared state machine returned by createSharedMachine includes functions such as .send() to trigger state transitions and .getState() to return a snapshot of the current state. These mechanisms are implemented using React.useSyncExternalStore.

    Type Parameters

    • D

      The type of state machine definition.

    Parameters

    • machine: SharedMachine<D>

      The shared state machine.

    • OptionalgetServerState: (() => State<D>)

      A function that returns the state on the server.

    Returns [state: State<D>, send: Send<D>]

    An array with two elements:

    • The first element is the current state of the state machine.
    • The second element is a function that sends an event to the state machine.
    import { useSharedMachine, createSharedMachine } from "use-machine-ts"

    const network = createSharedMachine({
    // definition
    {
    initial: "inactive",
    states: {
    inactive: {
    on: { ONLINE: "active" },
    },
    active: {
    on: { OFFLINE: "inactive" },
    },
    },
    },
    })

    window.addEventListener("online", () => network.send("ONLINE"))
    window.addEventListener("offline", () => network.send("OFFLINE"))

    function NetworkStatus() {
    const [state] = useSharedMachine(network)

    return (
    <p>
    Network status: {state.value}
    </p>
    )
    }