When you use a router in {insert framework here} you are going to need to in a manor of speaking, define URLs that run functions (views) that render components, the interaction you would use to do this is typically held at the component level, button or link is clicked, handler function is called, sound about right?
Good to hear it rings a bell, now before we continue on, can I point out a massive problem with this. Html links are usable in any codebase, router links are not, if you had to, I mean in a pinch, could you swap frameworks to something else? The center of your universe revolves around React, Vue, Angular, other, your Api might be a service in JavaScript but sadly your navigation cannot be decoupled, or can it?
What if you could decouple and bring strictness to your navigation, remove unexpected results (customers arriving in places they are not supposed be yet), generate free state charts (nice diagrams) describing the flow of your navigation and also control even how back and reload should navigate, I believe I have accidentally found the answer, the answer lies with state machines.
If you don't know what state machines are, you probably do but didn't know it yet. A door for example, it has 4 states:
- open
- closed
- ajar
- error
You cannot walk through a closed door that would result in an error and perhaps a bloody nose.
You can open a close door or an ajar door but not an (fully) open door.
You can close an open or ajar door.
You can do pretty much do anything with an error, you already walked into a door, couldn't get any worse.
You cannot open a door yet also close it, cloning it's very fabric and breaking physics.
So there we go, a state machine is a series of states that contain rules.
Navigation is freely controled by the user but oftentimes we want the user to flow around our application in a controlled way, xstate can be used in a way that allows us to define or states and rules, but what's really awesome, you cannot access those rules until you transition to another state, rules are scoped, encapsulated and very strict. I'm here to tell you that you should not route directly by button click but instead send messages to your Router Machine.
Enough theory, geeez!
... COVID happened, I didn't finish this post. Decided to pull the trigger, if you like this I will do my first ever tutorial post. 馃槝