Skip to content

Instantly share code, notes, and snippets.

@ryanflorence
Created January 26, 2019 15:57
Show Gist options
  • Save ryanflorence/1390b82d3397b2e926929d3e1d50595b to your computer and use it in GitHub Desktop.
Save ryanflorence/1390b82d3397b2e926929d3e1d50595b to your computer and use it in GitHub Desktop.
import { useState, useMemo, useEffect } from "react";
import { interpret } from "xstate/lib/interpreter";
export default function useMachine(machine, { log = false } = {}) {
const [current, setCurrent] = useState(machine.initialState);
const service = useMemo(() => interpret(machine), []);
useEffect(() => {
service.onTransition(setCurrent).start();
return () => service.stop();
}, []);
useEffect(
() => {
if (log) {
console.group(current.value);
console.log("event", current.event);
console.log("state:", current.value);
console.log("next: ", current.nextEvents.join(", "));
console.log("context", current.context);
console.groupEnd(current.value);
}
},
[log, current.value]
);
return [current, service.send];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment