Search code examples
javascriptreactjsstatefinite-automatastate-machine

In react, does a finite state machine replace the role of a router?


I discovered finite state machines as an alternative to managing UI state in a react application. I think they are excellent but I am a little confused about how I should be using them.

Should I be building a state machine for the entire app or do I build little machines within each route?


Solution

  • Based on this spectrum discussion I learned that you can replace a router with a state chart.

    For example, https://state-machine-yzgnuxxwmg.now.sh/

    However, the first paragraph of https://statecharts.github.io/how-to-use-statecharts.html recommends using statecharts at the component level when starting out.

    When you first learn about statecharts, you might get the feeling that statecharts can be used to describe the entire behaviour of an application, all the way from which screens show as part of logging in, to the state of each checkbox and text field in every screen, all represented in a statechart. That would be a statechart from hell, and an even bigger maintenance burden. Instead, the focus should be to get a grip on the behaviour at the component level, whatever a component might be. A single screen would be a component, for sure. A single text field that might have some particular internal behaviour (e.g. it changes color based on various flags like required or invalid) might warrant that to be wrapped in a component with a statechart to describe its behaviour.