Simpler React component design with the Chain of Responsibility pattern
Tags: react, beginners, webdev, computerscience
Published: 2019-08-03 20:51:05

React is a great front-end development library, which is working with the speed of light and is easy to pick up and start to work with it. It utilizes simple concepts and mainly uses common JavaScript knowledge to build up single page applications, instead of creating exotic abstractions on top of the well-known front-end layer. React works with components based architecture to build up the UI. Your application will be a component, which can contain other components nested into each other.

Frameworks, like Angular or Vue enforce a structure on your code, with React you are not bound to folders or best practices by the library. This means, that if you do not act carefully, you can end up with a very deeply nested, codependent component graph, which will be very hard to unit test, let alone maintain.

There are some interesting ideas based on great experience on how to separate different types of logic into different types of containers ([here](https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0)). This solves the issue of coupling the data fetching logic and the data presentation logic. The main idea behind most of these approaches is to make parts of the application code independent and small, in order to prevent too high complexity.

# The problem what I faced
I count myself a reasonably experienced full stack web developer, who initially started with the Microsoft based stack, but since then I've broadened my repertoire. Despite that I learn React for only like 20 days I have seen similar problems in other domains several times.

To learn React, I've started to get as much information about it as I can. I've started to listen to podcasts, read discussions and even skimmed a book. After I thought I had what I needed to fuel my curiosity, I started to build a project to cut my teeth into real problems. My application is a news portal with articles all over the place.

The problem that resulted in this post was about one of my components which was meant to display article headlines and metadata about the article. One article can have three different state in my application:

- An article can be **invisible** - filtered out from presentation, with the searching 
 - An article can be still **loading** - and for practice I've decided to put skeleton articles in the place of the ones still not loaded.
 - And finally and article can be **fully presented** on the app.

Let's see some simplified code example for this:

    import React from 'react';
    class Article extends React.Component {
    
      constructor(props) {
        super(props);
        this.state = { articles : [] };
      }
      
      async componentDidMount() {
        const result = await fetch('http://sample.com/');
        const articles = await result.json();
        this.setState({articles: articles});
      }
      
      render() {
        return this.state.articles.map( article => {
          if (!article.visible) return <React.Fragment />;
          else if (article.loading) {
            return <div className="article skeleton" />;
          }
          else {
            return (
              <div className="article">
                {article.title}
              </div>);
          }
        });
      }
    }
    export default Article;

Of course the skeleton and the fully rendered article were a little more complex than this dummy example above, overall the render method for this component was more then 100 lines! A lot of lines means a higher complexity than what I like to deal with at once. 

# The pattern arrives to save the day...

As I saw this, I started to formulate the idea, that maybe it is time to use the Chain of Responsibility pattern to make the component understandable for a glance. As [RefactoringGuru](https://refactoring.guru/design-patterns/chain-of-responsibility) states:

> **Chain of Responsibility** is a behavioral design pattern that lets you pass requests along a chain of handlers. Upon receiving a request, each handler decides either to process the request or to pass it to the next handler in the chain.

This really seems like something we could use here to simplify this complex render function. Imagine to have the following handlers:

 1. Invisible article handler - if the article is not visible it renders an empty fragment, else it passes the request along.
 2. Loading article handler - if the article is loading, it renders the skeleton, else it passes the request along.
 3. Full article handler - renders the full article.

So, we need to create these handlers and a way to chain them one after another. Consider the following UML diagram from [Wikipedia](https://en.wikipedia.org/wiki/Chain-of-responsibility_pattern), to understand how the implementation works:
![Chain of Responsibility React JS - JSX](https://upload.wikimedia.org/wikipedia/commons/6/6a/W3sDesign_Chain_of_Responsibility_Design_Pattern_UML.jpg)The **Handler** will keep a list of all handlers in order, which will try to process the incoming request from the **Sender** (in our case the sender is the render method). Once **Reciever1** gets the request it decides whether it can handle it or not. If not, then it will call back to the **Handler** to pass the request to the next handler (receiver on the picture). This goes on until one receiver actually handles the request.

In the implementation I wanted to use as many features of ES6, as I could - so I can learn more out of this.

# The solution
Let's create first the actual handlers, which will process the requests, and later on focus on the mechanism to chain them together.

First write a handler to handle the request if the article is invisible, if not, just call back to the parent object to handle the request.

    import React from 'react';
    class InvisibleArticleHandler extends ArticleHandler {
      handleRequest = article => {
        if (!article.visible) {
          return <React.Fragment />;
        }
        return super.handleRequest(article);
      }
    }
    export default InvisibleArticleHandler;

Next, write a handler to handle the request if the article is loading, if not, just call back  to the parent object to handle the request.

    import React from 'react';
    class LoadingArticleHandler extends ArticleHandler {
      handleRequest = article => {
        if (article.loading) {
          return <div className="article skeleton" />;
        }
        return super.handleRequest(article);
      }
    }
    export default LoadingArticleHandler;
    
Last, write a handler to handle the request if the article is fully loaded.

    import React from 'react';
    class FullArticleHandler extends ArticleHandler {
      handleRequest = article => (
            <div className="article">
              {article.title}
            </div>
      );
    }
    export default FullArticleHandler;
    
Now it is time to write the parent class, that is extended in the concrete handlers. This class is keeping tack of the handlers.

    class ArcticleHandler {
    
      constructor() {
        this.handlers = [];
        }
        
      addHandler = handler => { this.handlers.push(handler); }
        
      empty = () => { this.handlers = []; }
        
      handleRequest(arcticle) {
        // FIFO - get the first handler from the array of handlers.
        const nextHandler = this.handlers.shift();

        // Pass the list of handlers to the concrete reciever object,
        // as when it is calling into it's parent's method, the call
        // is on that object, not on the original handler!
        nextHandler.handlers = this.handlers;
        return nextHandler.handleRequest(arcticle);
      }
    }
    export default ArcticleHandler;

Using this, we can end up with a lot more readable article component to present the news:

    import React from 'react';
    import ArcticleHandler from './ArcticleHandler';
    import InvisibleArticleHandler from './InvisibleArticleHandler';
    import LoadingArticleHandler from './LoadingArticleHandler';
    import FullArticleHandler from './FullArticleHandler';
    
    class Article extends React.Component {
    
      constructor(props) {
        super(props);
        this.state = { articles : [] };
      }
      
      async componentDidMount() {
        const result = await fetch('http://sample.com/');
        const articles = await result.json();
        this.setState({articles: articles});
      }
      
      render() {
        const articleHandler = new ArticleHandler();
        return this.state.articles.map( article => {
          // Reset the handlers for each article
          articleHandler.empty();
          articleHandler.addHandler(new InvisibleArticleHandler());
          articleHandler.addHandler(new LoadingArticleHandler());
          articleHandler.addHandler(new FullArticleHandler());
          return arcticleHandler.handleRequest(arcticle);
        });
      }
    }
    export default Article;

With utilizing the **Chain of Responsibily** pattern the render method can be written with a domain specific language, so next time you come by this method you will see, that it will try to render an article based on rules in the described order. 

I really hope that I provided some value to you with giving you the insight I got from tackling a complexity related issue. I will continue to post here in the future my next findings from my journey to learn React properly.

Any comments / feedback is more than welcome, either here or on my Twitter @Xavios5 !