---
title: "Comment by Jb Rocher on \"Untangling your Logic using State Machines\" | Hashnode"
description: "Great work ! It&#39;s always interesting to try implementing a pattern from scratch before switching to a fully fledged library like Xstate. It got me thinking,"
url: "https://hashnode.com/posts/untangling-your-logic-using-state-machines/615fc05db945c81a907cf8c7/comment/61631f8b53401f641ba10a20"
---

[Discussion](https://hashnode.com/posts/untangling-your-logic-using-state-machines/615fc05db945c81a907cf8c7)

Comment [Untangling your Logic using State Machines](https://hashnode.com/posts/untangling-your-logic-using-state-machines/615fc05db945c81a907cf8c7)

[Jb Rocher](https://hashnode.com/@jibrocher)

[Oct 10, 2021](https://hashnode.com/posts/untangling-your-logic-using-state-machines/615fc05db945c81a907cf8c7/comment/61631f8b53401f641ba10a20)

Great work ! It's always interesting to try implementing a pattern from scratch before switching to a fully fledged library like Xstate.

It got me thinking, I think you could take it one step further, while still avoiding any third-party dependency. Right now your `changeState` doesn't guarantee that you machine will be executed as described by your diagram.

For example nothing prevents you from calling `changeState('fadeOut')` from the state `invisible` which shouldn't be possible.

This could be solved by implementing the transition function from the [mathematical defintion](https://en.wikipedia.org/wiki/Finite-state_machine)

Something like that :

First you'd add the transition to your state defintion

```

const buttonStates = {
  // You could also map these to a number instead of the same string,
  // but this is personal preference as it's easier to debug.
  fadingOut: {
    show: "visible",
    hide: "invisible"
  },
  visible: {
    reset: "visible",
    fade: "fadingOut"
 },
  invisible: "{
    show: "visible"
  }
};
```

Then the transition function could be defined like so:

```

 const transition = (state, event) => {
    return buttonStates[state][event]
}
```

Which would allow you to call `transition(button.state, "fade")`

Might be overkill for your use case, but thought it was worth mentioning :)
