Finite State Machine Router (for React)
A finite state machine + declarative URL routing (for React).
Summary
A finite state machine (FSM) is mathematical concept used to describe a flow of information from one layout (or state) to another according to a set of rules (or transitions). FSMs are described as "a limited number of states and corresponding transitions from these states into other states."
In front-end web development we'll use FSMs to render the proper user interface and to transition into other UI views. Furthermore, we'll integrate our FSM with a routing mechanism so our URLs and state resolution can be handled automatically - hence Finite State Machine Router!
Rules:
- Always Atomic - State machine always resolves to an atomic node (states that have no child states).
- No Conditions - State machine assumes all data is present to render a state it and its entire lineage (down to an atomic node, as per rule #1). Having no conditional rendering logic within components lends itself well to determinism, making our app more predictable.
- Events Rule - Favor event emission instead of URL pushes in order to change states. Deriving an atomic state lineage from a URL is achievable, but not favorable.
- Order Matters - When no
initial
state is declared, the first state in document order is rendered. Similarly, when multiple transitions may apply to an emitted event, the first one in document order is selected while discarding the rest.
Examples:
Basic
First, let's compose our app in our standard index.jsx
// Index.jsximport Link Machine State Transition from 'fsm-router'; <Machine ='wood'> <State ='app' ='/wood'> <Transition ='error' ='error'/> <Transition ='not-found' ='not-found'/> <State ='home' => <Transition ='browse' ='browse'/> </State> <State ='browse-wrapper' ='/browse'> <State ='browse' =/> <State ='species' = ='/:speciesId'/> </State> <State ='error' =/> <State ='not-found' =/> </State></Machine>
What's going on here?
<Machine/>
is our top level component that we provide with a unique name.<State/>
conveys the UI components in a familiar tree hierarchy. Most of the time, you'll supply acomponent
attribute which accepts a React component.<Transition/>
outline the rules on how we get from one<State/>
to another. They are activated by emittingevents
, and are only valid when inside an active<State/>
lineage.
Now, let's write some components.
// Home.jsxconst Home = children history machine: send match <div> <h1>Intro Page!</h1> <button =>Browse Wood Selection</button> </div>
Notice the components props. You should be familiar with children
, React's default argument for allowing hierarchy. What's new are history
, machine
, and match
, which are all populated automatically when our component is supplied to <State component={Home}/>
.
Pay special attention to machine.send()
. This is how we dispatch events to our state machine in order to activate transitions. In this particular example, send('browse')
would cause our state machine to exit the home
state and enter the browse
state. The URL would update automatically according to our path
attributes.
Let's keep going.
// Browse.jsxconst Browse = children history machine match const selection = summary: 'Northern red oak is a hardwood with a pleasing aesthetic, making it ideal for sturdy home furniture.' id: 'northern-red-oak' species: 'Northern Red Oak' summary: 'Pine is a common softwood, often characterized as having many knots.' id: 'pine' species: 'Pine' summary: 'Poplar wood is a lightweight, softwood and straight-grained, making it ideal for small kit projects.' id: 'poplar' species: 'Poplar' ; return <div> <h1>Wood selection</h1> <ul> selection </ul> </div>
Although we want to favor emitting events instead of pushign URLs, we can still push URLs. To do this, we'll use the <Link/>
component. This is utlimately a wrapper for the native <a/>
browser anchor tag, but uses history.push
to update URls instead of replace. This is to prevent page reloads on URL changes.
// Species.jsxconst Species = childre history machine match const species set = ; const exact // true params // { 'speciedId': 'northern-red-oak' } path // '/:speciesId' url // '/browse/northern-red-oak' = match; return <div> <h1>Wood species: speciesname</h1> <h2>Id: matchparamsspeciesId</h2> <p>Description: speciesdescription</p> </div>}
Finally, we have access to all the various routing parameters with match
. This is most useful for when you need to obtain a dynamic URL variable - for example, we've declared path='/:speciesId'
which may look like /northern-red-oak
in the URL.
With API fetching
Here's how we're going to organize our API requests:
App.jsx
container component makes API request to get some data.- To re-dispatch the API request in
App.jsx
, we can click the "refresh" button. - Once the user lands on
/browse
, we're going to make another API request in ourBrowseFetch
component.
Because we don't want to include conditional render logic in our component (upholding No Conditions rule), we'll want to initially render loaders within each component that we're fetching data. Once resolved, we'll simply send
machine events to transition from our loader components into our data-rich components.
// Index.jsx<Machine ='wood'> <State ='app' = ='/wood'> <Transition ='fetch' ='app-loader'/> <State ='app-loader' => <Transition ='resolve' ='home'/> <Transition ='reject' ='error'/> </State> <State ='home' => <Transition ='browse' ='browse'/> </State> <State ='browse-wrapper' ='/browse' => <State ='browse-loader' => <Transition ='resolve' ='browse'/> <Transition ='reject' ='error'/> </State> <State ='browse' =/> <State ='species' = ='/:speciesId'/> </State> </State> <State ='error' =/> <State ='not-found' =/></Machine> // App.jsxconst App = children history machine: send match const _fetch = ; ; return <div> <button =>Refresh</button> children </div> // BrowseFetch.jsxconst BrowseFetch = children history machine: send match
useMachine
hook
If you need access to the state machine outside of a standard React component, you can use the useMachine
hook.
import useMachine from 'fsm-router'; const machine: current history id params send = ;
API
References:
License
MIT License Copyright (c) 2020-present, Matthew Morrison