An array with two elements:
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>
)
}
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 bycreateSharedMachine
includes functions such as.send()
to trigger state transitions and.getState()
to return a snapshot of the current state. These mechanisms are implemented usingReact.useSyncExternalStore
.