Created
October 31, 2018 20:01
-
-
Save audionerd/b096f3ffb7982a70957acaff31ced105 to your computer and use it in GitHub Desktop.
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