using xstate with react hooks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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