5

Vintage concepts, fresh applications — CS-in-JS

 3 years ago
source link: https://engineering.thetrainline.com/vintage-concepts-fresh-applications-cs-in-js-af85be4ed487
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Vintage concepts, fresh applications — CS-in-JS

Last month I was lucky enough to attend React Amsterdam where there were dozens of amazing talks. I recommend you check out D3 and React, Together, Cross Language React and Mixed Mode React. There was one talk, however, that caught my attention: setState Machine by Facebook’s Michele Bertoli.

The premise was simple, some people call it CS-in-JS: take a classic Computer Science concept and apply it directly to modern web development.

In the case of setStateMachine, the proposition is using finite state machines for web UI state management. Michele has created an open source library, react-automata (based on xstate) that does just that, but in React! Here’s the description from the react-automata website:

A state machine abstraction for React that provides declarative state management and automatic test generation.

Let’s explore how it works.

What is a state machine?

A finite state machine is a mathematical abstraction that defines (1) a finite set of states that a machine (or program) can be in and (2) given the current state of the machine, what is the state the machine will be in after a given event occurs.

State machines are often represented visually where a circle represents a state of the machine and the arrow represents an action that occurs. Take the below representation of a finite state machine:

Image for post
Image for post
Image Credit: O’Reilly — Erlang Programming by Francesco Cesarini, Simon Thompson

In this example, if our machine were in State 1, and Event 1 occurred, the next state would still be State 1. If then Event 2 occurred, the system would now be in State 2.

Let’s check out this real world example of how a turnstile could be programmed by a finite state machine:

Image for post
Image for post
Image Credit — Wikipedia: Turnstile & Finite-state machine

We begin (marked by the black dot) in the ‘Locked’ state. If someone tries to simply push through the turnstile — the action — the diagram will return to the ‘Locked’ state because no coin was used. If then the person deposited a coin, the machine would switch to be in ‘Un-locked’ state and go back to ‘Locked’ only after the person pushed through to the other side.

Finite-state machines can be mathematically deterministic, that is it will always produce the same output from a given input.

What does this mean for UI development on the web?

This principle can be applied to keeping the state of UI components. Imagine deterministically defining the state of a toggle button, a collapsible drawer, an animation or even lazy loading for infinite scroll. The properties of finite-state machines can also aid, like react-automata does, in auto generating snapshot tests to make sure the actions transition into the correct states.

It can be a good way of making sense of complex UI state management that can quickly turn unwieldy with traditional approaches, especially for loading or async states.

Using finite-state machines can have tons of benefits when programming UI components in modern web applications:

  • You can decouple the UI component from its behaviour and declaratively define its behaviour in a way that allows you to more easily reason about the code and spot any possible missing states.
  • The behaviour of your component can be tested independently and, in some cases, with automatically generated tests.
  • It’s a great communication tool. By defining all the states up front, the behaviour of the component can be very easily defined and communicated to other developers, testers, designers and other stakeholders.

It’s worth noting that, much like most approaches to web development, finite state machines are not a silver bullet for state management. There are, however, an increasing number of resources online that deal with this topic!

How can we use this in React ?

Let’s look at one of the react-automata examples. Assume we wanted to build a web app to search for images on Flickr. We want our user interface to show a search bar to begin with, a spinner or loading state while it’s fetching the data, and an image gallery once it is successful.

Sample App from react-automata docs, we’ll explore a version of this

Let’s represent those states as a Javascript object:

Image for post
Image for post

Now let’s define what the next state will be, given certain actions

Image for post
Image for post
If on ‘search’ state, on SEARCH action, transition to ‘loading’ state

To finish up our state chart we’ll indicate which state is the initial state, and we’ll assign to each state to run on entry to that state (or on exit):

Image for post
Image for post

Now that we’ve defined the “finite-state machine” for our photo gallery. Let’s add it to a React component!

We’re gonna import some help from react-automata and create a skeleton of what the full app could look like:

/* ...imports... */
import { Action, withStatechart } from 'react-automata'const statechart = { ... }class Gallery extends React.Component {
state = {
searchQuery = '',
disableFormInput = false, }
enterLoadingFunction() { /* set state, disable form * /}
exitLoadingFunction() { /* remove some state * /}
enterGalleryFunction() { /* ... * /} render() {
<Input isDisabled={this.state.disableForm}/>
<SearchButton onClick={this.props.transition('SEARCH')} />
}/* react-automata provides a statechart higher order component to apply state rules to component, provides "transition" function as prop */const App = withStatechart(statechart)(MyReactComponent)ReactDOM.render(<App />, document.getElementById('root'))

Where can I learn more?

If you want to see what that app could look like in it’s entirety, check out the source-code here and learn more about react-automata library on the repo here.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK