install#
shell
npm install @cassiozen/usestatemachine
shell
npm install @cassiozen/usestatemachine
Sample Usage#
ts
const [state, send] = useStateMachine({
initial: 'inactive',
states: {
inactive: {
on: { TOGGLE: 'active' },
},
active: {
on: { TOGGLE: 'inactive' },
effect() {
console.log('Just entered the Active state');
// Same cleanup pattern as `useEffect`:
// If you return a function, it will run when exiting the state.
return () => console.log('Just Left the Active state');
},
},
},
});
Â
console.log(state); // { value: 'inactive', nextEvents: ['TOGGLE'] }
Â
// Refers to the TOGGLE event name for the state we are currently in.
Â
send('TOGGLE');
Â
// Logs: Just entered the Active state
Â
console.log(state); // { value: 'active', nextEvents: ['TOGGLE'] }
ts
const [state, send] = useStateMachine({
initial: 'inactive',
states: {
inactive: {
on: { TOGGLE: 'active' },
},
active: {
on: { TOGGLE: 'inactive' },
effect() {
console.log('Just entered the Active state');
// Same cleanup pattern as `useEffect`:
// If you return a function, it will run when exiting the state.
return () => console.log('Just Left the Active state');
},
},
},
});
Â
console.log(state); // { value: 'inactive', nextEvents: ['TOGGLE'] }
Â
// Refers to the TOGGLE event name for the state we are currently in.
Â
send('TOGGLE');
Â
// Logs: Just entered the Active state
Â
console.log(state); // { value: 'active', nextEvents: ['TOGGLE'] }