Boost your React with State Machines
Jean-Paul Delimat
1.5K5

Hey, I’m excited that you’re considering the usage of state machines in React applications — they definitely do cut down the complexity of your app as your app grows.

However, (and I’m sorry, I really hate to be that guy) there’s a few concerns I have with your approach. The biggest is that this is not a proper finite state machine, because it lacks transitions. There is nothing in the code that indicates that “when the user is in state A, and event E happens, transition to state B”. This is crucially important for FSMs in UIs, because it enumerates what is allowed to be done, and what state transitions the user can make.

If this were a real app, and I click “submit”, but I continue editing, chances are, I’m going to have an unexpected result. What value will be submitted? The pre-submit value or the post-submit value?

You can also do this with much, much less boilerplate. I’ve written an article about this and would recommend it, if you are looking to integrate a working state machine with very little boilerplate and no libraries: https://css-tricks.com/robust-react-user-interfaces-with-finite-state-machines/

I’m happy your article mentioned the intuition about boolean flags being an unscalable way to handle finite app states, though. That’s an important point and valuable insight. This is all a great start.

If you’d like to continue the conversation (would be happy to hear your thoughts!) you can join the statecharts community at https://spectrum.chat/statecharts.