Skip to content

Instantly share code, notes, and snippets.

@audionerd
Created October 31, 2018 20:01
Show Gist options
  • Save audionerd/b096f3ffb7982a70957acaff31ced105 to your computer and use it in GitHub Desktop.
Save audionerd/b096f3ffb7982a70957acaff31ced105 to your computer and use it in GitHub Desktop.
using xstate with react hooks
import React, { useState, useEffect, useMemo } from 'react'
import { Machine } from 'xstate'
import { interpret } from 'xstate/lib/interpreter'
const toggleMachine = Machine({
id: 'toggle',
initial: 'inactive',
states: {
inactive: {
on: { TOGGLE: 'active' }
},
active: {
on: { TOGGLE: 'inactive' }
}
}
})
function Toggle () {
const [current, setCurrent] = useState(toggleMachine.initialState)
const service = useMemo(() =>
interpret(toggleMachine)
, [ toggleMachine])
useEffect(() => {
service.onTransition(setCurrent)
service.start()
return function cleanup () {
service.off(setCurrent)
service.stop()
}
}, [service])
const { send } = service
return (
<button onClick={() => send('TOGGLE')}>
{current.matches('inactive') ? 'Off' : 'On'}
</button>
)
}
export default Toggle
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment