<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Xavios</title>
    <description>The latest articles on DEV Community by Xavios (@xavios5).</description>
    <link>https://dev.to/xavios5</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F206339%2F2d26118b-ddf0-4504-981c-38f1e05e561e.png</url>
      <title>DEV Community: Xavios</title>
      <link>https://dev.to/xavios5</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/xavios5"/>
    <language>en</language>
    <item>
      <title>Simpler React component design with the Chain of Responsibility pattern</title>
      <dc:creator>Xavios</dc:creator>
      <pubDate>Sat, 03 Aug 2019 20:51:05 +0000</pubDate>
      <link>https://dev.to/xavios5/simpler-react-component-design-with-the-chain-of-responsibility-pattern-319o</link>
      <guid>https://dev.to/xavios5/simpler-react-component-design-with-the-chain-of-responsibility-pattern-319o</guid>
      <description>&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;There are some interesting ideas based on great experience on how to separate different types of logic into different types of containers (&lt;a href="https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0" rel="noopener noreferrer"&gt;here&lt;/a&gt;). 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.&lt;/p&gt;

&lt;h1&gt;
  
  
  The problem what I faced
&lt;/h1&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;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:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;An article can be &lt;strong&gt;invisible&lt;/strong&gt; - filtered out from presentation, with the searching 

&lt;ul&gt;
&lt;li&gt;An article can be still &lt;strong&gt;loading&lt;/strong&gt; - and for practice I've decided to put skeleton articles in the place of the ones still not loaded.&lt;/li&gt;
&lt;li&gt;And finally and article can be &lt;strong&gt;fully presented&lt;/strong&gt; on the app.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;/ul&gt;

&lt;p&gt;Let's see some simplified code example for this:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;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 =&amp;gt; {
      if (!article.visible) return &amp;lt;React.Fragment /&amp;gt;;
      else if (article.loading) {
        return &amp;lt;div className="article skeleton" /&amp;gt;;
      }
      else {
        return (
          &amp;lt;div className="article"&amp;gt;
            {article.title}
          &amp;lt;/div&amp;gt;);
      }
    });
  }
}
export default Article;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;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. &lt;/p&gt;

&lt;h1&gt;
  
  
  The pattern arrives to save the day...
&lt;/h1&gt;

&lt;p&gt;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 &lt;a href="https://refactoring.guru/design-patterns/chain-of-responsibility" rel="noopener noreferrer"&gt;RefactoringGuru&lt;/a&gt; states:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Chain of Responsibility&lt;/strong&gt; 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.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This really seems like something we could use here to simplify this complex render function. Imagine to have the following handlers:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Invisible article handler - if the article is not visible it renders an empty fragment, else it passes the request along.&lt;/li&gt;
&lt;li&gt;Loading article handler - if the article is loading, it renders the skeleton, else it passes the request along.&lt;/li&gt;
&lt;li&gt;Full article handler - renders the full article.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;So, we need to create these handlers and a way to chain them one after another. Consider the following UML diagram from &lt;a href="https://en.wikipedia.org/wiki/Chain-of-responsibility_pattern" rel="noopener noreferrer"&gt;Wikipedia&lt;/a&gt;, to understand how the implementation works:&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fupload.wikimedia.org%2Fwikipedia%2Fcommons%2F6%2F6a%2FW3sDesign_Chain_of_Responsibility_Design_Pattern_UML.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fupload.wikimedia.org%2Fwikipedia%2Fcommons%2F6%2F6a%2FW3sDesign_Chain_of_Responsibility_Design_Pattern_UML.jpg" alt="Chain of Responsibility React JS - JSX"&gt;&lt;/a&gt;The &lt;strong&gt;Handler&lt;/strong&gt; will keep a list of all handlers in order, which will try to process the incoming request from the &lt;strong&gt;Sender&lt;/strong&gt; (in our case the sender is the render method). Once &lt;strong&gt;Reciever1&lt;/strong&gt; gets the request it decides whether it can handle it or not. If not, then it will call back to the &lt;strong&gt;Handler&lt;/strong&gt; to pass the request to the next handler (receiver on the picture). This goes on until one receiver actually handles the request.&lt;/p&gt;

&lt;p&gt;In the implementation I wanted to use as many features of ES6, as I could - so I can learn more out of this.&lt;/p&gt;

&lt;h1&gt;
  
  
  The solution
&lt;/h1&gt;

&lt;p&gt;Let's create first the actual handlers, which will process the requests, and later on focus on the mechanism to chain them together.&lt;/p&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from 'react';
class InvisibleArticleHandler extends ArticleHandler {
  handleRequest = article =&amp;gt; {
    if (!article.visible) {
      return &amp;lt;React.Fragment /&amp;gt;;
    }
    return super.handleRequest(article);
  }
}
export default InvisibleArticleHandler;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from 'react';
class LoadingArticleHandler extends ArticleHandler {
  handleRequest = article =&amp;gt; {
    if (article.loading) {
      return &amp;lt;div className="article skeleton" /&amp;gt;;
    }
    return super.handleRequest(article);
  }
}
export default LoadingArticleHandler;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Last, write a handler to handle the request if the article is fully loaded.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from 'react';
class FullArticleHandler extends ArticleHandler {
  handleRequest = article =&amp;gt; (
        &amp;lt;div className="article"&amp;gt;
          {article.title}
        &amp;lt;/div&amp;gt;
  );
}
export default FullArticleHandler;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now it is time to write the parent class, that is extended in the concrete handlers. This class is keeping tack of the handlers.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class ArcticleHandler {

  constructor() {
    this.handlers = [];
    }

  addHandler = handler =&amp;gt; { this.handlers.push(handler); }

  empty = () =&amp;gt; { 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;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Using this, we can end up with a lot more readable article component to present the news:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;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 =&amp;gt; {
      // 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;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;With utilizing the &lt;strong&gt;Chain of Responsibily&lt;/strong&gt; 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. &lt;/p&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;Any comments / feedback is more than welcome, either here or on my Twitter &lt;a class="mentioned-user" href="https://dev.to/xavios5"&gt;@xavios5&lt;/a&gt; !&lt;/p&gt;

</description>
      <category>react</category>
      <category>beginners</category>
      <category>webdev</category>
      <category>computerscience</category>
    </item>
  </channel>
</rss>
