State machine in JavaScript – How to build your own Redux like engine

This article will describe shortly how to build Redux-like state machine engine. So shortly what we need to define state machine?
– State itself (method which will deliver the state)
– Subscribe method (which will subscribe to state changes)
– Dispatch method (which will execute changes of our state engine)

Redux like engine – Step 1 – Draft of state management function

Lets define the draft of Redux-like function with previously defined methods getState, dispatch and subscribe. Parameter of our state managing function will be reducer – function which will describe how state should behave on given action.

const createStore = (reducer) => {
        let state;

        const getState = () => state;

        const dispatch = () => console.log('this method will execute change of state');

        const subscribe = () => console.log('this method will subscribe to changes on state);

        return {
            getState,
            dispatch,
            subscribe
        }
    };

Defined arrow function will return three methods:
1. getState – which will return our current state
2. dispatch – dispatcher of actions
3. subscribe – method which subscribes to state changes

Inside createStore function we defined state. This is the variable which keeps our current state. If we want to have a direct access to state we need to invoke getState method.

Redux like engine – Step 2 – Initial State

Our Redux-like engine won’t work without reducer and initial state. In this section let’s define initial state. Let’s imagine that we are developing game and one action of the game will be related to shots made by user. So when user will be clicking on screen or touching screen on mobile devices this action will be invoked. After invoking this action our state will be changed. In this case the number of shots made by user will be incremented. Initially it will be equal 0.

const initialState = {
    shots: 0
};

Redux like engine – Step 3 – Reducer

In this section we will define our reducer which will describe how our state should be changed after dispatching / executing given action. Reducer will get two params:
1. Initial state (defined previously)
2. Action

Action is an object with two parameters:
1. type
2. payload

Initially we will describe how our state should behave when user will invoke SHOT action.

const reducer = (state = initialState, action) => {
    switch (action.type) {
        case 'SHOT':
           state = {
                ...state,
                shots: state.shots +1
            }
            return state;
        default:
            return state;
    }
}

To make interpretation of our reducer function lets imagine that we want to invoke action SHOT. To do it we have to pass to reducer action object like

{
    type: 'SHOT'
}

Redux like engine – Step 4 – Body of state management function

Let’s make our state usable. To do it we need to define two methods inside it
1. subscribe
2. dispatch

Before subscribe function will be created we have to define listeners inside createStore. Listeners will be an array of elements which will subscribe to our state and will react on each change of the state.

const createStore = (rootReducer) => {
    let state;
    let listeners = [];

    const getState = () => state;

    const dispatch = action => {
        state = rootReducer(state, action);
        listeners.forEach(listener => listener(state));
    };

    const subscribe = (listener) => {
        listeners.push(listener);

        return () => {
            listeners = listeners.filter(l => l !== listener)
        }
    };

    return {
        getState,
        dispatch,
        subscribe
    }
};

Redux like engine – Step 5 – Combine and run

Lets make a short tests. In this subchapter we will combine reducer and our statemanagement engine. At the end of code we will make an instance of store, we will subscribe to it and will get its value.

const initialState = {
    shots: 0
};

const reducer = (state = initialState, action) => {
    switch (action.type) {
        case 'SHOT':
          console.log('shot')
           state = {
                ...state,
                shots: state.shots +1
            }
            return state;
        default:
            return state;
    }
};

const createStore = (rootReducer) => {
    let state;
    let listeners = [];

    const getState = () => state;

    const dispatch = action => {
        state = rootReducer(state, action);
        listeners.forEach(listener => listener(state));
    };

    const subscribe = (listener) => {
        listeners.push(listener);

        return () => {
            listeners = listeners.filter(l => l !== listener)
        }
    };

    return {
        getState,
        dispatch,
        subscribe
    }
};

const storeInstance = createStore(reducer);

console.log(storeInstance.getState());

storeInstance.subscribe(() => console.log('subscriber shots:', + storeInstance.getState().shots))

storeInstance.dispatch({type: 'SHOT'});
storeInstance.dispatch({type: 'SHOT'});
storeInstance.dispatch({type: 'SHOT'});

console.log(storeInstance.getState());

After running this code we will see console log similar to this one:

"shot"
"subscriber shots:" 1
"shot"
"subscriber shots:" 2
"shot"
"subscriber shots:" 3
[object Object] {
  shots: 3
}

Everytime “dispatch” function is ran it gives us information about sum of shots. Additionally we can see that reducer function is ran (“shot” log).

State management – Isn’t it easy? 😀

4 thoughts on “State machine in JavaScript – How to build your own Redux like engine

  1. For me, using a state machine means asking the right questions. This approach simply leads to higher level of predictability. We see how the state machine pattern protects our app being in a wrong state or state that we don’t know about. There is no conditional logic in the view layer because the machine is capable of providing information of what should be rendered. I’ve made Stent because I wanted state machines in my applications and at the same time I didn’t want to stop using Redux. I took lots of stuff from Redux and this is the result. We still have actions which are handled by reducers. The saga pattern is built-in so we can handle side effects in a synchronous fashion. Stent knows the possible actions upfront and it generates methods which in the context of Redux we call action creators. This always bugs me a little because in order to dispatch an action in Redux application I have to define a constant and then an action creator. Later somewhere in the code import it and finally call it. With Stent is just a method of the machine.

  2. How the application looks like really doesn’t matter. Here is a list of components that are the same for both implementations. They are presentational components which simply render stuff and fire callbacks. You may easily skip this section and jump directly to the Redux implementation. It’s here just for a reference.

Leave a Reply to Patrick Cancel reply

Your email address will not be published. Required fields are marked *