end

Next lesson: Redux - the predictable state container To the next lesson →

Lesson: State machines Repeat

§ Your JavaScript app is made of state machines

In this video, we will introduce the concept of state machines in JavaScript and how they can be used to model and manage the state of an object or system.

A state machine is a mathematical model of computation that describes the behavior of a system as a sequence of states, transitions between those states, and actions that are taken when entering or leaving a state. State machines can be used to model a wide range of systems, from simple programs to complex systems like traffic lights or vending machines.

Here's the example of the state machine that we implemented in the video lesson:

const IDLE = 'IDLE';
const LOADING = 'LOADING';
const SUCCESS = 'SUCCESS';
const ERROR = 'ERROR';

const state = {
  currentState: IDLE,
  products: null
};

const machine = {
  [IDLE]: {
    [LOADING]: async () => {
      try {
        state.products = await loadData();
        machine.transitionTo(SUCCESS);
      } catch(error) {
        machine.transitionTo(ERROR);
      }
    }
  },
  [LOADING]: {
    [SUCCESS]: () => {
      render();
    },
    [ERROR]: () => {
      render();
    }
  },
  transitionTo(newState) {
    if (machine[state.currentState][newState]) {
      const func = machine[state.currentState][newState];
      state.currentState = newState;
      render();
      func();
    } else {
      throw new Error(`${newState} doesn't make sense`);
    }
  }
}

There are a couple of important concepts while implementing such logic.

  • We first define our states. In the example above those are IDLE, LOADING, SUCCESS and ERROR.
  • We define the possible transitions out of each of the states.
  • We have a mechanism to perform a transition. (The transitionTo function).
questionnaire

Practice

Practice is the fastest way to learn knowledge permanently. I have prepared a small task for you related to the lesson.

Practice
discussion

Materials

Materials related to the lesson:
Files associated with the lesson

Materials

Next: Redux - the predictable state container(06:48)

To the lesson →