Caleb Oki I'm a freelance web developer and designer. I passionately move pixels and lines of code to craft clean, responsive, and user-friendly websites. My current weapons of choice are PHP Zend framework, jQuery, angularJS and MySQL.

State management patterns in JavaScript: Sharing data across components

13 min read 3775

When we talk about state management what we are really talking about is, how do we manage data across the components of a JavaScript application?

A typical challenge found in building many applications is keeping different parts of the user interface synchronized. Often, changes to the state need to be reflected in multiple components, and as the application grows this complexity only increases.

A common solution is to use events to let different parts of the application know when something has changed. Another approach is to keep state within the DOM itself or even assign it to a global object in the window. Nowadays we have several libraries such as Vuex, Redux, and NgRx to help make managing state across components easy. They generally use what is known as a store pattern where all actions that mutate or change the store’s state are put inside a single Store class. This type of centralized state management makes it easier to understand what type of mutations could happen and how they are triggered.

What we will build

Any state management tool needs only a couple of things: a global state value available to the entire application, as well as the ability to read and update it. The general idea is as follows:

const state = {};

export const getState = () => state;

export const setState = nextState => {
  state = nextState;
};

This is a very basic example that shows a globally-available value representing the application’s state: state, a method for reading state: getState and a method for updating state: setState. We would use this general idea to build a to-do list application with no JavaScript frameworks or dependencies. In the process, we will get a broad overview of how these state libraries work under the hood. The application will look like this:

To begin, we want to install http-server which will serve our application after we are done. To install this, first make sure you have Nodes.js and the Nodes.js package manager (NPM) installed on your machine. On a Windows operating system, the steps to install these are:

  1. Download the Windows installer from the Nodes.js web site
  2. Run the installer you just downloaded
  3. Follow the prompts, accepting the default installation settings
  4. Test it by running node-v in the terminal. This should print a version number so you’ll see something like this v8.12.0. Also, run npm -v to see if NPM was successfully installed. This should print NPM’s version number so you’ll see something like this 6.4.1.
  5. Run the command npm install http-server -g to install http-server globally on your machine. After this is installed, you can now serve your application by running http-server in the directory where your index file exists

Now moving back to building our application, create a folder structure as shown below:

/state-management-JS
   ├──src
      ├── css
         ├── global.css
      ├── js
         ├── main.js
      index.html

In the global.css file, enter the following:

 h1 {
    margin-bottom: 15px;
    width: 100%;
    font-size: 100px;
    font-weight: 100;
    text-align: center;
    color: rgba(175, 47, 47, 0.15);
    -webkit-text-rendering: optimizeLegibility;
    -moz-text-rendering: optimizeLegibility;
    text-rendering: optimizeLegibility;
}
@media all and (min-width: 40em) {
    main {
        width: 80vw;
        max-width: 40em;
        margin: 0 auto
    }
}
/**
* Intro 
*/
.intro {
    padding: 0 0 1rem 0;
    margin: 0 0 2rem 0;
    border-bottom: 1px dotted var(--border);
}
.intro__heading {
    font-weight: 400;
}
.intro__summary {
    margin-top: 0.3rem;
    font-size: 1.3rem;
    font-weight: 300;
}
.intro__summary b {
    font-weight: 500;
}
/**
* App 
*/
.app {
    display: grid;
    grid-template-columns: 1fr;
    grid-auto-flow: row;
    grid-gap: 2rem;
}
.app__decor {
    display: block;
    width: 100%;
    text-align: center;
    font-size: 3rem;
    line-height: 1;
}
.app__decor small {
    display: block;
    font-size: 1.3rem;
    font-weight: 400;
    color: var(--text-secondary);
}
.app__decor > * {
    display: block;
}
.app__decor > * + * {
    margin-top: 0.4rem;
}
.app__items {
    list-style: none;
    padding: 0;
    margin: 1rem 0 0 0;
    font-weight: 300;
}
.app__items li {
    position: relative;
    padding: 0 0 0 2rem;
    font-size: 1.3rem;
}
.app__items li::before {
    content: "🕛";
    position: absolute;
    top: 1px;
    left: 0;
}
.app__items li + li {
    margin-top: 0.5rem;
}
.app__items button {
    background: transparent;
    border: none;
    position: relative;
    top: -1px;
    color: var(--danger);
    font-weight: 500;
    font-size: 1rem;
    margin: 0 0 0 5px;
    cursor: pointer;
}
.app__items button:hover {
    color: var(--danger--dark);
}
@media all and (min-width: 40rem) {
    .app {
        grid-template-columns: 2fr 1fr;
    }
}

/**
* New item
*/
.new-item {
    margin: 2rem 0 0 0;
    padding: 1rem 0 0 0;
    border-top: 1px dotted var(--border);
}

/**
* No items
*/
.no-items {
    margin: 1rem 0 0 0;
    color: var(--text-secondary);
}
/**
* Visually hidden
*/
.visually-hidden { 
    display: block;
    height: 1px;
    width: 1px;
    overflow: hidden;
    clip: rect(1px 1px 1px 1px);
    clip: rect(1px, 1px, 1px, 1px);
    clip-path: inset(1px);
    white-space: nowrap;
    position: absolute;
}
.new-todo {
    padding: 16px 16px 16px 60px;
    border: none;
    background: rgba(0, 0, 0, 0.003);
    box-shadow: inset 0 -2px 1px rgba(0,0,0,0.03);
    position: relative;
    width: 100%;
    font-size: 24px;
    font-family: inherit;
    font-weight: inherit;
    line-height: 1.4em;
}
.save-button {
    display: inline-block;
    border: 0;
    padding: 0;
    margin: 0;
    text-decoration: none;
    background: #666;
    color: #fff;
    padding: 11px 25px 10px 25px;
    font-family: sans-serif;
    font-size: 1rem;
    border-radius: 2px;
    cursor: pointer;
    text-align: center;
    -webkit-appearance: none;
    margin-top: 15px;
}

This is the style-sheet we will use for our application. We won’t talk about styles in this tutorial as there is nothing specific about applying styles to the application.

The Observer pattern

We are going to make use of the Observer architectural design pattern which is language agnostic. The Observer pattern offers a subscription model in which objects subscribe to an event and get notified when the event occurs. This pattern is the cornerstone of event-driven programming, including JavaScript. The Observer pattern facilitates good object-oriented design and promotes loose coupling.

Representation of the Observer pattern

Observers are also called Subscribers and we refer to the object being observed as the Publisher (or the subject). Publishers notify subscribers when events occur.

When objects are no longer interested in being notified by the subject they are registered with, they can unsubscribe themselves. The subject will then, in turn, remove them from the observer collection.

Open up the src\js directory, then create a new folder called lib. Inside this folder create a new file called pubsub.js. The structure of your js folder should look like this:

/js
   ├── lib
      ├── pubsub.js

In this file, we are creating the functionality to allow other parts of our application to subscribe to and publish named events.

Enter the following code to pubsub.js

export default class PubSub {
    constructor() {
        this.events = {};
    }
    subscribe(event, callback) {
        if (!this.events.hasOwnProperty(event)) {
            this.events[event] = [];
        }
        return this.events[event].push(callback);
    }
    publish(event, data = {}) {
        if (!this.events.hasOwnProperty(event)) {
            return [];
        }
        return this.events[event].map(callback => callback(data));
    }
}

In the constructor, we are instantiating this.events to an empty object which will hold our events.

The subscribe method accepts a string event, which is the event’s unique name and a callback function. Then it checks if this.events has a matching event among its properties-if the event is not found, it creates the event property as a blank array. Otherwise, it pushes the passed callback method into this.events[event].

The publish method checks if this.events has a matching event among its properties-if the event is not found it returns an empty array. Otherwise, it loops through each stored callback with the data object as an argument.

The store

Next let’s create a central object which will contain a state object that in turn, contains our application state. We will also create a dispatch method which would be called when a user enters a new to-do item. This method calls our action which in turn calls our mutations which finally changes the state.

Create a new folder in your js folder called store. In there, create a new file called store.js so that your folder structure should look like this:

/js
   ├── lib
      ├── pubsub.js
   ├── store
      ├── store.js

Then enter the following into store.js

import PubSub from '../lib/pubsub.js';

export default class Store {
    constructor(params) {
        let self = this;
        self.actions = {};
        self.mutations = {};
        self.state = {};
        self.status = 'default state';
        self.events = new PubSub();
        if (params.hasOwnProperty('actions')) {
            self.actions = params.actions;
        }
        if (params.hasOwnProperty('mutations')) {
            self.mutations = params.mutations;
        }
        self.state = new Proxy((params.state || {}), {
            set: function (state, key, value) {
                state[key] = value;
                console.log(`stateChange: ${key}: ${value}`);
                self.events.publish('stateChange', self.state);
                if (self.status !== 'mutation') {
                    console.warn(`You should use a mutation to set ${key}`);
                }
                self.status = 'resting';
                return true;
            }
        });
    }
    dispatch(actionKey, payload) {
        let self = this;
        if (typeof self.actions[actionKey] !== 'function') {
            console.error(`Action "${actionKey} doesn't exist.`);
            return false;
        }
        console.groupCollapsed(`ACTION: ${actionKey}`);
        self.status = 'action';
        self.actions[actionKey](self, payload);
        console.groupEnd();
        return true;
    }
    commit(mutationKey, payload) {
        let self = this;
        if (typeof self.mutations[mutationKey] !== 'function') {
            console.log(`Mutation "${mutationKey}" doesn't exist`);
            return false;
        }
        self.status = 'mutation';
        let newState = self.mutations[mutationKey](self.state, payload);
        self.state = Object.assign(self.state, newState);
        return true;
    }   
}

Let’s examine what this code is doing. First, we are importing the pubsub.js file. We then declare a constructor which accepts an argument. Inside this, we instantiate a default empty objects for state, actions, and mutations. We are also adding a status property that we’ll use to determine what the object is doing at any given time. We then create a new instance of PubSub and assign it to the property events. Then we check if the argument passed into the constructor has the property actions and mutations as it’s own property. If either condition is true, we set the actions and the mutations object to the corresponding parameter of the passed in argument.

Next, we use the new ES6 feature, Proxy to watch the state object. If we add a get trap, we can monitor every time that the object is asked for data. Similarly, with a set trap, we can keep an eye on changes that are made to the object. In our context though, we’re setting the change and then logging it to the console. We’re then publishing a stateChange event with our PubSub module. Then we are checking if status is not a mutation and logging a warning in the console to that effect.

Next, we have the dispatch method which looks for an action and, if it exists, set a status and call the action while creating a login console. The action will then mutate our changes by calling the commit method. In this method, we are checking if a mutation exists, if so we run it and get our new state from its return value. We then take that new state and merge it with our existing state to create an up-to-date version of our state.

Actions and mutations

Now let’s create the action and mutation files which we referred to in the previous section. In your store folder, create a new file called actions.js and add the following to it:

export default {
    addItem(context, payload) {
        context.commit('addItem', payload);
    },
    clearItem(context, payload) {
        context.commit('clearItem', payload);
    }
};

The context, is the instance of the Store class and the payload is the actual data change, passed in by the dispatch method in the Store class. The actions addItem and clearItem is passing the payload to a mutation-the commit method which, in turn, commits the data to store. Let’s now create our mutation. Create a new file, still in the store folder called mutations.js:

export default {
    addItem(state, payload) {
        state.items.push(payload);
        return state;
    },
    clearItem(state, payload) {
        state.items.splice(payload.index, 1);
        return state;
    }
};

As explained previously this mutation is called by the commit method in our action.js file. Here addItem accepts our current state and a payload as an argument, then pushes the payload into an items property of the state object. The second method, clearItem removes the payload passed in from the state object.

Next, let’s create a file which would hold default set of items so that on first-load our application will have something to display. In the same folder, create a file state.js and enter the following:

export default {  
    items: [
        'An example task. Delete or add your own',
        'Another example task. Delete or add your own'
    ]
};

Create another file called index.js in the same directory, in which we will import our actions, mutations, state and store. Enter the following in this file:

import actions from './actions.js';
import mutations from './mutations.js';
import state from './state.js';
import Store from './store.js';

export default new Store({
  actions,
  mutations,
  state
});

Components

Our application has just three functionalities: show a list of tasks, add tasks and show a count of tasks. We will separate out these functionalities into three component files, but first we will create a base component. Create a file called component.js in the lib folder. So your lib folder structure looks like this:

├── lib
   ├── pubsub.js
   ├── component.js

In the component.js file, enter the following:

import Store from '../store/store.js';
export default class Component {
    constructor(props = {}) {
        this.render = this.render || function () { };
        if (props.store instanceof Store) {
            props.store.events.subscribe('stateChange', () => this.render());
        }
        if (props.hasOwnProperty('element')) {
            this.element = props.element;
        }
    }
}

Here we are importing the Store class which we will use to check one of our properties in the constructor. In the constructor we’re looking to see if we’ve got a render method. If this Component class is the parent of another class, then the child class will have likely set its own method for render. If there is no method set, we create an empty method that will prevent things from breaking.

Next, we check if the passed in object has a property that is an instance of the Store class which we imported. We do this so we can confidently use its methods and properties. Then we call the subscribe method, passing in the name of the event we are subscribing to-the global stateChange event and the callback render. Finally, we get an element property from our child component

Now that we have the parent component, let’s create the child components. First, create a new folder called components inside the js folder. In this folder create a file called list.js. Your js folder structure should look like this:

/js
   ├── lib
   ├── components
      ├── list.js

In the list.js file, enter the following:

import Component from '../lib/component.js';
import store from '../store/index.js';
export default class List extends Component {
    constructor() {
        super({
            store,
            element: document.querySelector('.js-items')
        });
    }
    render() {
        
        if (store.state.items.length === 0) {
            this.element.innerHTML = `<p class="no-items">You have no tasks yet </p>`;
            return;
        }
        this.element.innerHTML = `
      <ul class="app__items">
        ${store.state.items.map(item => {
            return `
            <li>${item}<button aria-label="Delete this item">×</button></li>
          `
        }).join('')}
      </ul>
    `;
        this.element.querySelectorAll('button').forEach((button, index) => {
            button.addEventListener('click', () => {
                store.dispatch('clearItem', { index });
            });
        });
    }
};

Here in the constructor, we are using the super keyword to access and call functions on our parent’s component, that is the components.js file. We start off by passing our Store instance up to the parent class that we are extending.

After that, we declare a render method that gets called each time the stateChange event happens. This is also the method the parent component.js checks for. In this render method we put out either a list of items or a little notice if there are no items. You’ll also see that each button has an event attached to it and they dispatch and action within our store.

Next, let’s create the count component. Create a new file called count.js in the same folder and enter the following:

import Component from '../lib/component.js';
import store from '../store/index.js';
export default class Count extends Component {
    constructor() {
        super({
            store,
            element: document.querySelector('.js-count')
        });
    }
    render() {
        let suffix = store.state.items.length !== 1 ? 's' : '';
        this.element.innerHTML = `
      You have
      ${store.state.items.length}
      task${suffix} today 
    `;
    }
}

This handles the count of our items and it is self-explanatory. Let’s move on to the last component. Create a new file called status.js and enter the following:

import Component from '../lib/component.js';
import store from '../store/index.js';
export default class Status extends Component {
    constructor() {
        super({
            store,
            element: document.querySelector('.js-status')
        });
    }
}

Views

The last thing we need to do is to create a main.js file and the index.html view. In the js folder create the main.js file and enter the following:

import store from './store/index.js';
import Count from './components/count.js';
import List from './components/list.js';
import Status from './components/status.js';
const formElement = document.querySelector('.js-form');
const inputElement = document.querySelector('#new-item-field');
formElement.addEventListener('submit', evt => {
    evt.preventDefault();
    let value = inputElement.value.trim();
    if (value.length) {
        store.dispatch('addItem', value);
        inputElement.value = '';
        inputElement.focus();
    }
});
const countInstance = new Count();
const listInstance = new List();
const statusInstance = new Status();
countInstance.render();
listInstance.render();
statusInstance.render();

Here all we’re doing is pulling in dependencies that we need. We’ve got our Store, our front-end components and a couple of DOM elements to work with. Next, we are adding an event listener to the form and preventing it from submitting using preventDefault. We then grab the value of the textbox and trim any whitespace off it. We do this because we want to check if there’s actually any content to pass to the store next. Finally, if there’s content, we dispatch our addItem action with that content

Then we are creating new instances of our components and calling each of their render methods so that we get our initial state on the page.

In the src folder create the index.html file, and enter the following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <link rel="stylesheet" href="css/global.css" />
    <link rel="stylesheet" href="https://bootswatch.com/4/flatly/bootstrap.css" />
    <title>Todo</title>
</head>
<body>
    <main>
        <header class="intro">
            <h1 class="intro__heading">Todo List</h1>
        </header>
        <section class="app">
            <section class="app__input">
                <h2 class="app__heading">Tasks</h2>
                <div class="js-items" aria-live="polite" aria-label="A list of items you have to done"></div>
                <form class="new-item js-form ">
                  <div>
                    <input type="text" class="new-todo" id="new-item-field" autocomplete="off" placeholder="What is to be done"/>
                    <button class="btn-primary save-button">Save</button>
                  </div>
                </form>
        </section>
          <aside class="app__status">
            <p role="status" class="visually-hidden"><span class="js-status"></span></p>
              <div class="app__decor js-count" aria-hidden="true">
              </div>
          </aside>
        </section>
    </main>
    <script type="module" src="js/main.js"></script>
</body>
</html>

LocalStorage

Using terminal, cd into the src folder and run the command http-server. This will serve our application in a local web server. Now visit the URL http://localhost:8080 to view the application. Go ahead and add something like “Read book” in there.

You will notice that when we refresh the page, the data we entered is lost. We need a way to persist or store the data we entered. LocalStorage lets us store data in the browser, which can be retrieved even when the user closes or reloads the page. We also have the ability to write, update and delete data from localStorage. We can get item using the method localStorage.getItem, set item using the method localStorage.setItem and remove item using the method localStorage.removeItem.

Let’s setup localStorage in our application. In the /src/js/store/mutations.js file, replace the content with:

export default {
    addItem(state, payload) {
        state.items.push(payload);
        localStorage.setItem('items', JSON.stringify(state.items))   
        return state;
    },
    clearItem(state, payload) {
        state.items.splice(payload.index, 1);
        localStorage.setItem('items', JSON.stringify(state.items))
        return state;
    }
};

In the addItem method, after pushing the payload into the state object, we are converting state.items into a string and storing it in localStorage with key name items. We are doing a similar same thing in the clearItem method, hereafter removing an item from state.items, we are updating localStorage with the updated value of state.items.

Next in /src/js/store/state.js, replace its content with:

export default {
    items: JSON.parse(localStorage.getItem('items') || '[]')   
};

Here we are checking localStorage if a key named items exists. If it does, we want to set it to the variable items otherwise set items to an empty array. Now our application can retain the data we entered even when we reload or close the page.

For those more advanced

If you recall in the store.js file, we made use of an ES6 feature, Proxy to monitor the state object. What this essentially does is wraps an existing object, also known as the target and intercept any access to its attributes or methods even if they do not exist. The proxy object has some traps, that can be called before granting access to the target. Here we are using the set trap to keep an eye on changes that are made to the state object. That means that when a mutation runs something like state.name ="Foo" , this trap catches it before it can be set. Some use cases for proxies include validation, value correction, property lookup extensions, tracing property accesses and many more.

Conclusion

We have explored how to implement state management in JavaScript. In the process, we have learned about the Observer architectural design pattern and localStorage. There are many scenarios where you will need to implement state management, one of which is user management and authentication. You can look at the final product on Github and if you have any questions or comments, don’t hesitate to post them below.

Plug: LogRocket, a DVR for web apps

https://logrocket.com/signup/

LogRocket is a frontend logging tool that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.

In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single page apps.

Try it for free.

Caleb Oki I'm a freelance web developer and designer. I passionately move pixels and lines of code to craft clean, responsive, and user-friendly websites. My current weapons of choice are PHP Zend framework, jQuery, angularJS and MySQL.

Leave a Reply