<?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: Thanh Truong</title>
    <description>The latest articles on DEV Community by Thanh Truong (@thanhtr99270163).</description>
    <link>https://dev.to/thanhtr99270163</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%2F292513%2F5cea2ceb-0983-4524-9458-1e63940437d1.jpg</url>
      <title>DEV Community: Thanh Truong</title>
      <link>https://dev.to/thanhtr99270163</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/thanhtr99270163"/>
    <language>en</language>
    <item>
      <title>React - Meet Virtual DOM</title>
      <dc:creator>Thanh Truong</dc:creator>
      <pubDate>Wed, 09 Feb 2022 10:53:41 +0000</pubDate>
      <link>https://dev.to/thanhtr99270163/react-meet-virtual-dom-3lk2</link>
      <guid>https://dev.to/thanhtr99270163/react-meet-virtual-dom-3lk2</guid>
      <description>&lt;p&gt;We briefly discussed the features of React in the &lt;a href="https://dev.to/thanhtr99270163/react-meet-and-greet-8c1"&gt;introductory post&lt;/a&gt; of this series. In this article, we will dive deeper into the &lt;strong&gt;&lt;em&gt;declarative programming&lt;/em&gt;&lt;/strong&gt; aspect of React by exploring React's &lt;strong&gt;&lt;em&gt;virtual DOM.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Y9fGXgAT--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res-2.cloudinary.com/under-the-hood-learning/image/upload/q_auto/v1/blog_images/Concept-Map---Virtual-DOM-Focused.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Y9fGXgAT--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res-2.cloudinary.com/under-the-hood-learning/image/upload/q_auto/v1/blog_images/Concept-Map---Virtual-DOM-Focused.png" alt="React - Meet Virtual DOM" width="880" height="495"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;A major theme in React is a drive to simplify otherwise complex tasks and abstract unnecessary complexity away from the developer. React tries to do just enough to be &lt;strong&gt;&lt;em&gt;performant&lt;/em&gt;&lt;/strong&gt; while freeing you up to think about other aspects of your application. One of the main ways it does that is by promoting &lt;strong&gt;&lt;em&gt;declarative&lt;/em&gt;&lt;/strong&gt; instead of &lt;strong&gt;&lt;em&gt;imperative&lt;/em&gt;&lt;/strong&gt; programming. You get to declare how your components should behave and look under different states, and React's internal machinery handles the complexity of managing updates, updating the UI to reflect changes, etc. One of the major pieces of technology driving this is the &lt;strong&gt;virtual DOM.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A &lt;strong&gt;&lt;em&gt;virtual DOM&lt;/em&gt;&lt;/strong&gt; is a data structure that mimics the &lt;strong&gt;Document Object Model (DOM)&lt;/strong&gt; in the browsers. React is not the only framework using a virtual DOM. Other frameworks such as &lt;strong&gt;Ember&lt;/strong&gt; employ their own implementation of a virtual DOM. A virtual DOM serves as an intermediate layer between the application code and the browser DOM. The virtual DOM allows the complexity of &lt;strong&gt;&lt;em&gt;change detection and management&lt;/em&gt;&lt;/strong&gt; to be hidden from the developer and moved to a specialized layer of abstraction. React's virtual DOM handles change detection in data as well as translating browser events into events that React components can understand and react to.&lt;/p&gt;

&lt;h2&gt;
  
  
  The DOM
&lt;/h2&gt;

&lt;p&gt;To understand virtual DOM, we first need to understand the DOM. If you're already familiar with the DOM, feel free to jump ahead to the next section.&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;Document Object Model (DOM)&lt;/strong&gt; is a programming interface that allows JavaScript programs to interact with different types of documents ( &lt;strong&gt;HTML, XML, SVG,&lt;/strong&gt; etc.). There are standards-driven specifications - a &lt;em&gt;standard set of features created by the public working group -&lt;/em&gt; for the DOM.&lt;/p&gt;

&lt;p&gt;The DOM provides a structured way of accessing, storing, and manipulating different parts of a document. At a high level, the DOM is a tree structure that reflects the hierarchy of an XML document. This tree structure is comprised of sub-trees that are in turn made of nodes as shown in the image below. The &lt;strong&gt;DOM API&lt;/strong&gt; that is exposed to JavaScript allows access and operations on each of these elements in the tree.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--t7jJI4SA--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res-2.cloudinary.com/under-the-hood-learning/image/upload/q_auto/v1/blog_images/DOM-tree.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--t7jJI4SA--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res-2.cloudinary.com/under-the-hood-learning/image/upload/q_auto/v1/blog_images/DOM-tree.png" alt="React - Meet Virtual DOM" width="614" height="420"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Whenever you use a method in JavaScript that accesses, modifies, or stores information related to something in an HTML document, you're using the DOM or its related API. Not all methods used in JavaScript are part of the JS language itself. In fact, they are part of a bigger collection of &lt;strong&gt;&lt;em&gt;web APIs.&lt;/em&gt;&lt;/strong&gt; For example, some common methods or properties that may be used to update or query a web page are: &lt;code&gt;getElementById&lt;/code&gt;, &lt;code&gt;parent.appendChild&lt;/code&gt;, &lt;code&gt;querySelectorAll&lt;/code&gt;, &lt;code&gt;innerHTML&lt;/code&gt;. These methods are provided by the host environment - the browser - and allow JS to interact with the DOM.&lt;/p&gt;

&lt;p&gt;In the context of a large web application, interacting with the DOM in this manner could get quite complicated. That's when &lt;strong&gt;virtual DOM&lt;/strong&gt; shines.😎&lt;/p&gt;

&lt;h2&gt;
  
  
  Virtual DOM
&lt;/h2&gt;

&lt;p&gt;As mentioned in the previous section, there are certain pain points when it comes to working directly with the DOM via the regular web APIs, especially when building large and complicated web applications. Generally, these pain points arise in the area of &lt;strong&gt;&lt;em&gt;change detection&lt;/em&gt;&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Particularly, when data changes, we need to update the UI to reflect that. However, doing that in a way that is efficient and easy to think about can be difficult due to the way browsers handle interactions with the DOM. When a DOM element is accessed, modified, or created, the browser is often performing a query across a structured tree to find a given element. It will then need to adjust the layout, sizing, and other actions as part of a mutation, all of which can be computationally expensive.&lt;/p&gt;

&lt;p&gt;A virtual DOM can help with optimizing DOM updates to account for these constraints. And that's exactly what React's virtual DOM aimed to solve, &lt;em&gt;i.e. implementing a virtual DOM that is **fast enough&lt;/em&gt;* while maintaining a robust API, simple mental model, and cross-browser compatibility.* The keyword here is &lt;strong&gt;&lt;em&gt;"fast enough"&lt;/em&gt;&lt;/strong&gt; because there is another factor that influences the design in React, which is &lt;strong&gt;&lt;em&gt;simplicity.&lt;/em&gt;&lt;/strong&gt; In other words, it must be simple enough to allow developers to defer extensive thinking about how the virtual DOM is accomplishing complicated state update logic and focus on the more important aspects of building their applications. Therefore, when building applications with React, we don't often need to directly interact with the DOM. Instead, we mostly leave that to React. &lt;strong&gt;&lt;em&gt;But, how does the virtual DOM work?&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;DOM mutation done poorly can be computationally expensive, so React tries to be efficient in its update to the UI by implementing a &lt;strong&gt;&lt;em&gt;diffing and update&lt;/em&gt;&lt;/strong&gt; procedure.&lt;/p&gt;

&lt;p&gt;React creates and maintains a &lt;strong&gt;&lt;em&gt;virtual DOM&lt;/em&gt;&lt;/strong&gt; in memory, and a renderer like &lt;code&gt;react-dom&lt;/code&gt; handles updating the browser DOM based on changes. React solves the performance issue by implementing &lt;strong&gt;&lt;em&gt;heuristic diffing&lt;/em&gt;&lt;/strong&gt; - a method to calculate which parts of the in-memory DOM require changes to the DOM and perform intelligent updates only on the parts that have changed as shown in the image below.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--H_XbcI3r--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res-2.cloudinary.com/under-the-hood-learning/image/upload/q_auto/v1/blog_images/React-heuristic-diffing-virtual-DOM.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--H_XbcI3r--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res-2.cloudinary.com/under-the-hood-learning/image/upload/q_auto/v1/blog_images/React-heuristic-diffing-virtual-DOM.png" alt="React - Meet Virtual DOM" width="880" height="618"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;To see the &lt;strong&gt;&lt;em&gt;heuristic diffing&lt;/em&gt;&lt;/strong&gt; mechanism in action, let's look at a simple example using both the native Web API and the React API for comparison purposes. To keep things simple, we will not be using &lt;strong&gt;&lt;em&gt;components&lt;/em&gt;&lt;/strong&gt; or &lt;strong&gt;&lt;em&gt;JSX&lt;/em&gt;&lt;/strong&gt; (the JavaScript extension that is used with React). Through this example, we will also learn about two core API methods: &lt;code&gt;ReactDOM.render&lt;/code&gt; and &lt;code&gt;React.createElement&lt;/code&gt;. These methods lay the foundation for our next article in which we get to learn about React components.&lt;/p&gt;

&lt;h2&gt;
  
  
  Heuristic Diffing
&lt;/h2&gt;

&lt;p&gt;Before we can use the React library, we need to somehow import it into our application code. We can do that using one of the following methods as suggested on the &lt;a href="https://reactjs.org/docs/react-api.html"&gt;React documentation&lt;/a&gt;. Once imported, the React's top-level APIs are available on the &lt;code&gt;React&lt;/code&gt; global variable.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Load React from a &lt;code&gt;&amp;lt;script&amp;gt;&lt;/code&gt; tag. The &lt;strong&gt;CDN links&lt;/strong&gt; for both the &lt;strong&gt;React&lt;/strong&gt; and &lt;strong&gt;ReactDOM&lt;/strong&gt; libraries can be found on the React &lt;a href="https://reactjs.org/docs/cdn-links.html"&gt;website&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;Use &lt;code&gt;import React from 'react'&lt;/code&gt; if using &lt;strong&gt;ES6&lt;/strong&gt; with &lt;strong&gt;npm.&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;Use &lt;code&gt;var React = require('react')&lt;/code&gt; if using &lt;strong&gt;ES5&lt;/strong&gt; with &lt;strong&gt;npm.&lt;/strong&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;To start off, let's render a simple HTML element to the display using two different methods: one from the native Web API, and the other from the React API as shown below.&lt;/p&gt;

&lt;p&gt;You should see a &lt;strong&gt;"Hello Native Web API"&lt;/strong&gt; box and a &lt;strong&gt;"Hello React"&lt;/strong&gt; box. Let's study the code.👩‍💻&lt;/p&gt;

&lt;p&gt;Basically, we have two nodes: &lt;code&gt;mountNode1&lt;/code&gt; is controlled with the &lt;strong&gt;DOM API&lt;/strong&gt; directly while &lt;code&gt;mountNode2&lt;/code&gt; is controlled with the &lt;strong&gt;React API,&lt;/strong&gt; which in turn uses the DOM API. The only major difference in how these two nodes were built is that in the DOM API version we used a string to represent the DOM tree, while in the React API version we used pure JavaScript calls and represented the DOM tree with an object instead of a string.&lt;/p&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;document.getElementById('mountNode').innerHTML = `
    &amp;lt;div&amp;gt;
    Hello Native Web API
  &amp;lt;/div&amp;gt;
`;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&amp;lt;!--kg-card-end: markdown--&amp;gt;&amp;lt;!--kg-card-begin: markdown--&amp;gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ReactDOM.render(
  React.createElement(
    'div', 
    null, 
    'Hello React',
  ),
  document.getElementById('mountNode2'),
);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's focus on the React API. The &lt;code&gt;ReactDOM.render&lt;/code&gt; and &lt;code&gt;React.createElement&lt;/code&gt; methods are the core API methods in a React application. In fact, a React web application cannot exist without using both of these methods.&lt;/p&gt;

&lt;h3&gt;
  
  
  ReactDOM Render
&lt;/h3&gt;

&lt;p&gt;This is basically the &lt;strong&gt;&lt;em&gt;entry point&lt;/em&gt;&lt;/strong&gt; for a React application into the browser's DOM.&lt;/p&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ReactDOM.render(element, container[, callback])

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It takes two required inputs and one optional input:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;element&lt;/code&gt;: The first input is a &lt;strong&gt;&lt;em&gt;React element,&lt;/em&gt;&lt;/strong&gt; which we will explore in the next section. Basically, this input dictates &lt;strong&gt;&lt;em&gt;WHAT&lt;/em&gt;&lt;/strong&gt; to render to the browser.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;container&lt;/code&gt;: A React element must be rendered inside a &lt;strong&gt;&lt;em&gt;container,&lt;/em&gt;&lt;/strong&gt; which is a valid DOM node that exists in the statically rendered HTML. In our example, it's the &lt;code&gt;&amp;lt;div&amp;gt;&lt;/code&gt; element with the &lt;code&gt;id=mountNode2&lt;/code&gt; specified in the &lt;code&gt;index.html&lt;/code&gt; file. Basically, the container dictates &lt;strong&gt;&lt;em&gt;WHERE&lt;/em&gt;&lt;/strong&gt; to render the React element in the browser.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;[callback]&lt;/code&gt;: If provided, the callback will be executed after the component is rendered or updated.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  React Element
&lt;/h3&gt;

&lt;p&gt;We mentioned &lt;strong&gt;React element&lt;/strong&gt; in the previous section. What exactly is a React element anyway? Well, long answer short, it's a &lt;strong&gt;&lt;em&gt;virtual element&lt;/em&gt;&lt;/strong&gt; describing a &lt;strong&gt;&lt;em&gt;DOM element.&lt;/em&gt;&lt;/strong&gt; The &lt;code&gt;React.createElement&lt;/code&gt; API method returns a React element.&lt;/p&gt;

&lt;p&gt;Instead of working with strings to represent DOM elements (as you've seen in the native Web API example above), DOM elements are represented as &lt;strong&gt;&lt;em&gt;objects&lt;/em&gt;&lt;/strong&gt; created by calling to the &lt;code&gt;React.createElement&lt;/code&gt; method. These objects are known as &lt;strong&gt;&lt;em&gt;React elements.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;React.createElement(
  type,
  [props],
  [...children]
)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above method has three arguments and returns a new &lt;strong&gt;React element&lt;/strong&gt; of the given &lt;strong&gt;&lt;em&gt;type&lt;/em&gt;&lt;/strong&gt; :&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;type&lt;/code&gt;: The &lt;code&gt;type&lt;/code&gt; argument can be either a &lt;strong&gt;&lt;em&gt;tag name&lt;/em&gt;&lt;/strong&gt; string (such as &lt;code&gt;'div'&lt;/code&gt; or &lt;code&gt;'span'&lt;/code&gt;), a &lt;strong&gt;&lt;em&gt;React component&lt;/em&gt;&lt;/strong&gt; type (a class or a function), or a &lt;strong&gt;&lt;em&gt;React fragment&lt;/em&gt;&lt;/strong&gt; type. In this example, we're passing &lt;code&gt;'div'&lt;/code&gt; as the type. We'll be covering React components and fragments in a future post.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;[props]&lt;/code&gt;: Any attributes (&lt;code&gt;id&lt;/code&gt;, &lt;code&gt;href&lt;/code&gt;, &lt;code&gt;title&lt;/code&gt;, etc.) we want the DOM elements to have. In this example, the &lt;code&gt;div&lt;/code&gt; element we're using has no attributes, so we passed in &lt;code&gt;null&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;[...children]&lt;/code&gt;: This argument forms the &lt;strong&gt;&lt;em&gt;children&lt;/em&gt;&lt;/strong&gt; list for the rendered element and is the content of the DOM element. An element can have zero or more children. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;No matter how complicated the UI is going to get, when using React every HTML element will be represented with a React element. React elements are created in memory. To actually make a React element show up in the DOM, we need to use the &lt;code&gt;ReactDOM.render&lt;/code&gt; method which will figure out the most optimal way to reflect the state of a React element into the actual DOM tree in the browser.&lt;/p&gt;

&lt;p&gt;To demonstrate how React elements can be nested, let's add a couple more elements to the current UI. Let's add a textbox to read input from the user and the current time displayed inside a &lt;code&gt;&amp;lt;pre&amp;gt;&lt;/code&gt; tag. We'll do that to both the native Web API and React API versions. As shown below, both the &lt;code&gt;&amp;lt;input&amp;gt;&lt;/code&gt; and &lt;code&gt;&amp;lt;pre&amp;gt;&lt;/code&gt; tags were added by making a nested &lt;code&gt;React.createElement&lt;/code&gt; method call inside of the top-level React element. Both versions should still be rendering the same exact HTML in the browser.&lt;/p&gt;

&lt;p&gt;At this point, you're probably thinking that using React is a lot harder than the simple and familiar native way. What is it that React does so well that makes it worth giving up the familiar HTML and having to learn a new API to create what can be simply created using the native Web APIs? The answer is not about the initial rendering of the HTML view. Rather, it's all about updating the existing view in the DOM. And that's when the &lt;strong&gt;&lt;em&gt;heuristic diffing&lt;/em&gt;&lt;/strong&gt; mechanism comes in handy.&lt;/p&gt;

&lt;h3&gt;
  
  
  Heuristic Diffing
&lt;/h3&gt;

&lt;p&gt;To demo this concept, let's add an update operation to the DOM trees which can be done using the &lt;code&gt;setInterval&lt;/code&gt; method from the Web timer API. But first, we'll need to put all of our DOM manipulations for both versions into a function, which we'll name as &lt;code&gt;render&lt;/code&gt;, and pass it into the &lt;code&gt;setInterval&lt;/code&gt; method as a callback in order to call it every second.&lt;/p&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const render = () =&amp;gt; {
  document.getElementById('mountNode').innerHTML = `
    &amp;lt;div&amp;gt;
      Hello HTML
      &amp;lt;input /&amp;gt;
      &amp;lt;pre&amp;gt;${new Date().toLocaleTimeString()}&amp;lt;/pre&amp;gt;
    &amp;lt;/div&amp;gt;
  `;

  ReactDOM.render(
    React.createElement(
      'div',
      null,
      'Hello React',
      React.createElement('input', null),
      React.createElement('pre', null, new Date().toLocaleTimeString())
    ),
    document.getElementById('mountNode2')
  );
};

setInterval(render, 1000);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Are you ready for what you're about to see next?😜 This is when React is going to blow your mind.💥 Now, try typing something into the textbox of the native Web API version. You won't be able to.😜 This is very much expected because we are basically throwing away the whole DOM node on every tick and regenerating it. However, try typing something in the textbox that is rendered with React. Magic!!!✨😎 So what's the difference?🤔&lt;/p&gt;

&lt;p&gt;Although the whole React rendering code is wrapped inside the ticking timer, React is only changing the content of the &lt;code&gt;&amp;lt;pre&amp;gt;&lt;/code&gt; element and not the whole DOM tree. In other words, the textbox was not regenerated, which is why you were able to type in it.&lt;/p&gt;

&lt;p&gt;You can see the difference in how the native Web API and the React API update the DOM visually by inspecting the two DOM nodes in the Chrome DevTools. As shown below, the native Web API regenerates the entire &lt;code&gt;&amp;lt;div id="mountNode1"&amp;gt;&lt;/code&gt; container with every tick, while React smartly regenerates only the &lt;code&gt;&amp;lt;pre&amp;gt;&lt;/code&gt; tag in its &lt;code&gt;&amp;lt;div id="mountNode2"&amp;gt;&lt;/code&gt; container.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--T1ftHVlw--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://res-2.cloudinary.com/under-the-hood-learning/image/upload/q_auto/v1/blog_images/Heuristic-Diff-Demo.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--T1ftHVlw--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://res-2.cloudinary.com/under-the-hood-learning/image/upload/q_auto/v1/blog_images/Heuristic-Diff-Demo.gif" alt="React - Meet Virtual DOM" width="618" height="308"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This is React's smart &lt;strong&gt;&lt;em&gt;diffing&lt;/em&gt;&lt;/strong&gt; algorithm in action. It only updates in the main DOM tree what actually needs to be updated while keeping everything else the same. This diffing process is possible because of React's virtual DOM representation that it keeps around in memory. No matter how many times the UI views need to be regenerated, React will take to the browser only the needed &lt;strong&gt;&lt;em&gt;partial updates.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Not only is this method a lot more efficient but it also removes a big layer of complexity in the way think about updating UIs. Having React do all the computations about whether we should or should not update the DOM enabled developers to focus on thinking about their data (&lt;strong&gt;&lt;em&gt;state&lt;/em&gt;&lt;/strong&gt;) and the way to &lt;strong&gt;&lt;em&gt;describe a UI&lt;/em&gt;&lt;/strong&gt; for it. Developers can focus on updates on the data state as needed without worrying about the steps needed to reflect these updates in the actual UI in the browser because React's got their backs.😉&lt;/p&gt;

</description>
      <category>react</category>
    </item>
    <item>
      <title>React - Meet and Greet</title>
      <dc:creator>Thanh Truong</dc:creator>
      <pubDate>Wed, 02 Feb 2022 11:09:57 +0000</pubDate>
      <link>https://dev.to/thanhtr99270163/react-meet-and-greet-8c1</link>
      <guid>https://dev.to/thanhtr99270163/react-meet-and-greet-8c1</guid>
      <description>&lt;p&gt;You have probably heard of &lt;strong&gt;React&lt;/strong&gt; in a discussion about other well-known JavaScript libraries and frameworks such as &lt;strong&gt;Vue, Angular, Ember, Webpack, Redux,&lt;/strong&gt; etc. We will kick-start this series with a quick introduction to React in the first two articles of this series.&lt;/p&gt;

&lt;p&gt;In this Part 1 article, we will:&lt;/p&gt;

&lt;blockquote&gt;
&lt;ul&gt;
&lt;li&gt;Settle the debate on whether React is a library or a framework, for good 😜&lt;/li&gt;
&lt;li&gt;Explore all the major ingredients that make up a React application&lt;/li&gt;
&lt;li&gt;Explore features of React at a high-level overview&lt;/li&gt;
&lt;/ul&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  Is it a library or a framework?
&lt;/h2&gt;

&lt;p&gt;Before we get started on learning about &lt;strong&gt;React,&lt;/strong&gt; I think it's important that we get this question answered because it has real consequences for our development process. And the answer to the million-dollar question is:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;React&lt;/strong&gt; is a ... &lt;strong&gt;LIBRARY&lt;/strong&gt;.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;🎉🎉🎉👏👏👏😁&lt;/p&gt;

&lt;p&gt;As a matter of fact, it's stated very clearly on their official website homepage.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--ilkEidkV--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res-1.cloudinary.com/under-the-hood-learning/image/upload/q_auto/v1/blog_images/2021-11-23-10_07_20-React---A-JavaScript-library-for-building-user-interfaces.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--ilkEidkV--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res-1.cloudinary.com/under-the-hood-learning/image/upload/q_auto/v1/blog_images/2021-11-23-10_07_20-React---A-JavaScript-library-for-building-user-interfaces.png" alt="React - Meet and Greet" width="880" height="344"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;React&lt;/strong&gt; is written in JavaScript, but unlike other popular JavaScript frameworks such as &lt;strong&gt;Angular, Vue, Svelte,&lt;/strong&gt; React is fundamentally unopinionated. But what does it even mean?&lt;/p&gt;

&lt;p&gt;It means that React itself does not include many of the React-specific libraries you're going to need for most projects. The React and React DOM libraries give us the means of building a user interface with the &lt;strong&gt;JSX&lt;/strong&gt; syntax, plus powerful state management tools via hooks, among other things. React does not enforce strict rules around code conventions or file organization allowing developer teams to set conventions that work best for them. Angular and Vue, by comparison, include many more tools all bundled within the core package itself.&lt;/p&gt;

&lt;p&gt;For example, when you set up an Angular project, it is bootstrapped with nearly every single thing that you'll need to make a complete, large-scale app. Some built-in tools included in Angular are tools for common tasks such as &lt;em&gt;creating forms, running automated tests, making network requests, etc.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;That being said, it doesn't necessarily mean that React cannot be used to build complex and large-scale applications. However, the implication is that the burden is on you as a developer to choose the packages and tools that you need in order to build your applications. For example, &lt;strong&gt;React Hook Form&lt;/strong&gt; or &lt;strong&gt;Formik&lt;/strong&gt; are React-specific form libraries, &lt;strong&gt;React Testing Library&lt;/strong&gt; and/or &lt;strong&gt;Jest&lt;/strong&gt; can be used for automated testing, &lt;strong&gt;Fetch API&lt;/strong&gt; or &lt;strong&gt;Axios&lt;/strong&gt; can be used for making network requests.&lt;/p&gt;

&lt;p&gt;The tools or libraries that you choose to use depend on the demands of the app and your preferences as a developer. This is one of the advantages of using React since it doesn't lock you into one choice or hold you to any specific libraries other than React itself. However, it does with a price because you will need to keep up with emerging libraries.&lt;/p&gt;

&lt;p&gt;It's worth noting that there are frameworks out there that are based on React if you ever need it. Some of the most popular frameworks are &lt;strong&gt;Next.js, Gatsby,&lt;/strong&gt; and &lt;strong&gt;Redwoord.js,&lt;/strong&gt; all of which are used to create full-scale dynamic and static React applications.&lt;/p&gt;

&lt;h2&gt;
  
  
  React's Major Ingredients
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;React's&lt;/strong&gt; mental model draws broadly on &lt;strong&gt;&lt;em&gt;functional&lt;/em&gt;&lt;/strong&gt; and &lt;strong&gt;&lt;em&gt;object-oriented programming&lt;/em&gt;&lt;/strong&gt; concepts and focuses on &lt;strong&gt;&lt;em&gt;components&lt;/em&gt;&lt;/strong&gt; as primary units for building with. In React applications, you create &lt;strong&gt;&lt;em&gt;interfaces&lt;/em&gt;&lt;/strong&gt; from components. React's &lt;strong&gt;&lt;em&gt;rendering system&lt;/em&gt;&lt;/strong&gt; manages these components and keeps the application view in sync for you.&lt;/p&gt;

&lt;p&gt;Components often correspond to aspects of the user interface such as &lt;em&gt;datepickers, headers, navbars, etc.,&lt;/em&gt; but they can also take responsibility for things like client-side routing, data formatting, styling, and other responsibilities of a client-side application. Components in React follow a predictable &lt;strong&gt;&lt;em&gt;lifecycle,&lt;/em&gt;&lt;/strong&gt; can maintain their own &lt;strong&gt;&lt;em&gt;internal state,&lt;/em&gt;&lt;/strong&gt; and work with regular old JavaScript.&lt;/p&gt;

&lt;p&gt;We will dive into these concepts in more detail in subsequent posts. For now, let's look at an overview of the major ingredients that go into a React application.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Components&lt;/strong&gt;
Components are _ &lt;strong&gt;encapsulated&lt;/strong&gt; _ units of functionality that are the primary unit in React. They utilize _ &lt;strong&gt;data&lt;/strong&gt; _ (_ &lt;strong&gt;properties&lt;/strong&gt; _ and _ &lt;strong&gt;state&lt;/strong&gt; _) to render your UI as output. Certain types of React components also provide a set of &lt;strong&gt;&lt;em&gt;lifecycle methods&lt;/em&gt;&lt;/strong&gt; that you can hook into. The &lt;strong&gt;&lt;em&gt;rendering process&lt;/em&gt;&lt;/strong&gt; outputs and updates the UI based on the data by interacting with the components via &lt;strong&gt;&lt;em&gt;React's APIs&lt;/em&gt;&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;React libraries&lt;/strong&gt;
React uses a set of &lt;strong&gt;&lt;em&gt;core libraries,&lt;/em&gt;&lt;/strong&gt; which work with the &lt;code&gt;react-dom&lt;/code&gt; and &lt;code&gt;react-native&lt;/code&gt; libraries and is focused on component specification and definition. Using these libraries, we can build a tree of components that a renderer for the browser or another platform can use. &lt;code&gt;react-dom&lt;/code&gt; is a renderer that is aimed at browser environments and server-side rendering, whereas &lt;code&gt;react-native&lt;/code&gt; focuses on iOS, Android, and other native platforms.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Third-party libraries&lt;/strong&gt;
React doesn't come with tools for data modeling, HTTP calls, styling libraries, or other common aspects of a front-end application. Therefore, developers are free to choose which additional modules or libraries they prefer to use.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  React Features
&lt;/h2&gt;

&lt;p&gt;Since we were browsing the React homepage, let's take a look at some of the features of React listed on the homepage to understand what this library promises to deliver.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--oZxjFtua--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res-1.cloudinary.com/under-the-hood-learning/image/upload/q_auto/v1/blog_images/2021-11-26-06_06_40-React---A-JavaScript-library-for-building-user-interfaces.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--oZxjFtua--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res-1.cloudinary.com/under-the-hood-learning/image/upload/q_auto/v1/blog_images/2021-11-26-06_06_40-React---A-JavaScript-library-for-building-user-interfaces.png" alt="React - Meet and Greet" width="880" height="645"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We will discuss these features at a high level and will dive deeper into the &lt;strong&gt;&lt;em&gt;declarative&lt;/em&gt;&lt;/strong&gt; and &lt;strong&gt;&lt;em&gt;component-based&lt;/em&gt;&lt;/strong&gt; concepts in the next article.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Declarative&lt;/strong&gt;
Declarative programming is not a new concept but just got popularized by React in the JavaScript community in recent years. According to Wikipedia:&lt;/li&gt;
&lt;/ol&gt;

&lt;blockquote&gt;
&lt;p&gt;Declarative programming is a programming paradigm — a style of building the structure and elements of computer programs—that expresses the logic of a computation without describing its control flow.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Component-Based&lt;/strong&gt;&lt;br&gt;&lt;br&gt;
When &lt;strong&gt;Facebook&lt;/strong&gt; released &lt;strong&gt;React.js&lt;/strong&gt; in 2013, it defined a new way in which front-end developers could build UI through a concept known as &lt;strong&gt;Component-Based Architecture (CBA),&lt;/strong&gt; a method for encapsulating individual pieces of a larger UI into self-sustaining, independent micro-systems.&lt;br&gt;&lt;br&gt;
Components have their own structure, their own methods, and their own API. Components are reusable, and their &lt;em&gt;"independent nature&lt;/em&gt; allows developers to create a UI with many moving parts, &lt;em&gt;e.g. one component can refresh without affecting other components or the UI as a whole.&lt;/em&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Learn Once, Write Anywhere&lt;/strong&gt;&lt;br&gt;&lt;br&gt;
Developers can use React to build applications for whatever platform they choose, without the need to learn a fundamentally different set of technologies. React can render on the server using &lt;strong&gt;Node&lt;/strong&gt; and power mobile apps using &lt;strong&gt;React Native.&lt;/strong&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  What's Next?
&lt;/h2&gt;

&lt;p&gt;For the remainder of this series, we will explore each of the core concepts of React as shown in the diagram below. Of course, listed here are just the core concepts that are typically encountered when building a React application. As we dive into each of these concepts, we will also discuss other relevant concepts as they come up.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--mYfIO3gP--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res-3.cloudinary.com/under-the-hood-learning/image/upload/q_auto/v1/blog_images/Concept-Map.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--mYfIO3gP--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res-3.cloudinary.com/under-the-hood-learning/image/upload/q_auto/v1/blog_images/Concept-Map.png" alt="React - Meet and Greet" width="880" height="482"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Virtual DOM:&lt;/strong&gt; React implements a virtual DOM that sits between your program and the browser DOM allowing for efficient updates to the DOM using a fast diffing algorithm. This is the core of React's &lt;strong&gt;&lt;em&gt;declarative programming.&lt;/em&gt;&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Component:&lt;/strong&gt; Components are the most fundamental unit of React. Component composition and reusability are some of the most powerful aspects of React. &lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Routes:&lt;/strong&gt; Routing is a system for resource navigation and is an important part of web applications. Different parts of your site will need their own URLs (for example, &lt;code&gt;/blogs&lt;/code&gt;, &lt;code&gt;/tags&lt;/code&gt;, &lt;code&gt;/about&lt;/code&gt;, etc.), and routing facilitates page navigation as it relates to URLs and resources such as images, HTML pages, scripts, etc.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Styling and CSS:&lt;/strong&gt; There are several options for styling a React app. We will discuss some of these options.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Data:&lt;/strong&gt; Modern web applications are mostly dynamic and filled with data that changes over time. We will explore how data flow between components via &lt;strong&gt;&lt;em&gt;props&lt;/em&gt;&lt;/strong&gt; and &lt;strong&gt;&lt;em&gt;states.&lt;/em&gt;&lt;/strong&gt; Lifecycle events are often used to handle various effects such as fetching data on the _ &lt;strong&gt;mount,&lt;/strong&gt; _ cleaning up before the component &lt;strong&gt;&lt;em&gt;unmounts,&lt;/em&gt;&lt;/strong&gt; sanitizing props when the components updates, etc. React provides &lt;strong&gt;&lt;em&gt;lifecycle methods&lt;/em&gt;&lt;/strong&gt; and &lt;strong&gt;&lt;em&gt;hooks&lt;/em&gt;&lt;/strong&gt; that can be used to &lt;strong&gt;&lt;em&gt;"hook"&lt;/em&gt;&lt;/strong&gt; into different parts of a component's lifetime.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Form:&lt;/strong&gt; Most web applications involve forms to one degree or another. We'll look at how to implement forms in React.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Redux:&lt;/strong&gt; Redux is a library and application architecture for state management that results in a highly predictable, testable, and debuggable application by enforcing strict ways of working with data.&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>react</category>
    </item>
    <item>
      <title>Observer Pattern with Vanilla JS</title>
      <dc:creator>Thanh Truong</dc:creator>
      <pubDate>Wed, 12 Jan 2022 11:07:55 +0000</pubDate>
      <link>https://dev.to/thanhtr99270163/observer-pattern-with-vanilla-js-1377</link>
      <guid>https://dev.to/thanhtr99270163/observer-pattern-with-vanilla-js-1377</guid>
      <description>&lt;p&gt;In the &lt;a href="https://dev.to/thanhtr99270163/mvc-architectural-design-pattern-with-vanilla-js-3lfa"&gt;previous article&lt;/a&gt;, we learned about the &lt;strong&gt;MVC&lt;/strong&gt; architectural pattern using vanilla JS. In this article, we will take another step further to improve our data flow between &lt;strong&gt;model, view,&lt;/strong&gt; and &lt;strong&gt;controller&lt;/strong&gt; by implementing the &lt;strong&gt;Observer&lt;/strong&gt; pattern.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;In this article, we will:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Explore ways to improve data flow for the existing MVC pattern.&lt;/li&gt;
&lt;li&gt;Learn about the problems that the &lt;strong&gt;Observer&lt;/strong&gt; is designed to solve.&lt;/li&gt;
&lt;li&gt;Learn what the &lt;strong&gt;Observer&lt;/strong&gt; pattern is all about.&lt;/li&gt;
&lt;li&gt;Explore how to implement the &lt;strong&gt;Observer&lt;/strong&gt; pattern using example from the previous article.&lt;/li&gt;
&lt;/ul&gt;
&lt;/blockquote&gt;

&lt;p&gt;In our MVC implementation, our &lt;strong&gt;controller&lt;/strong&gt; mediates the interaction between the &lt;strong&gt;view&lt;/strong&gt; and the &lt;strong&gt;model&lt;/strong&gt;, i.e. the  &lt;strong&gt;&lt;em&gt;view&lt;/em&gt;&lt;/strong&gt; triggers a change in the &lt;strong&gt;&lt;em&gt;model&lt;/em&gt;&lt;/strong&gt; through the  &lt;strong&gt;&lt;em&gt;controller&lt;/em&gt;&lt;/strong&gt;, and then the &lt;strong&gt;&lt;em&gt;model&lt;/em&gt;&lt;/strong&gt; updates the &lt;strong&gt;view&lt;/strong&gt;* through the &lt;strong&gt;&lt;em&gt;controller.&lt;/em&gt;&lt;/strong&gt; This setup is referred to as a  &lt;strong&gt;&lt;em&gt;two-way data flow.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--AWXAueNB--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res-4.cloudinary.com/under-the-hood-learning/image/upload/q_auto/v1/blog_images/MVC---Unidirection.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--AWXAueNB--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res-4.cloudinary.com/under-the-hood-learning/image/upload/q_auto/v1/blog_images/MVC---Unidirection.png" alt="Observer Pattern with Vanilla JS" width="880" height="495"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;With the &lt;strong&gt;Observer&lt;/strong&gt; pattern, we can turn the &lt;strong&gt;&lt;em&gt;model&lt;/em&gt;&lt;/strong&gt; into an  &lt;strong&gt;&lt;em&gt;"observable"&lt;/em&gt;&lt;/strong&gt; and the &lt;strong&gt;&lt;em&gt;view&lt;/em&gt;&lt;/strong&gt; into an &lt;strong&gt;&lt;em&gt;"observer".&lt;/em&gt;&lt;/strong&gt;  When the &lt;strong&gt;&lt;em&gt;observable&lt;/em&gt;&lt;/strong&gt; is changed, it &lt;strong&gt;&lt;em&gt;notifies&lt;/em&gt;&lt;/strong&gt; the  &lt;strong&gt;&lt;em&gt;observer&lt;/em&gt;&lt;/strong&gt; of its &lt;strong&gt;&lt;em&gt;state&lt;/em&gt;&lt;/strong&gt;, and the &lt;strong&gt;&lt;em&gt;observer&lt;/em&gt;&lt;/strong&gt; can react to that change. This makes our data flow &lt;strong&gt;&lt;em&gt;unidirectional.&lt;/em&gt;&lt;/strong&gt; The &lt;strong&gt;&lt;em&gt;controller&lt;/em&gt;&lt;/strong&gt; no longer updates the &lt;strong&gt;&lt;em&gt;view,&lt;/em&gt;&lt;/strong&gt; the &lt;strong&gt;&lt;em&gt;view&lt;/em&gt;&lt;/strong&gt; updates according to the &lt;strong&gt;&lt;em&gt;model.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--90E0YGsJ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res-5.cloudinary.com/under-the-hood-learning/image/upload/q_auto/v1/blog_images/MVC---Unidirection-2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--90E0YGsJ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res-5.cloudinary.com/under-the-hood-learning/image/upload/q_auto/v1/blog_images/MVC---Unidirection-2.png" alt="Observer Pattern with Vanilla JS" width="880" height="738"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;Observer&lt;/strong&gt; is a _ &lt;strong&gt;behavioral design pattern&lt;/strong&gt; _ that lets you define a _ &lt;strong&gt;subscription mechanism&lt;/strong&gt; _ to notify multiple objects about any events that happen to the object they're observing.&lt;/p&gt;

&lt;h2&gt;
  
  
  What problem does the Observer pattern solve?
&lt;/h2&gt;

&lt;p&gt;It's sometimes helpful to use a real-world analogy in order to understand the kind of problem that this pattern is designed to solve. Let's just say that you really enjoy the content published on my blog.😉 Instead of having to visit my site every day to check for new articles (not that I'm against that idea 😜), you could choose to subscribe to my &lt;a href="https://www.facebook.com/Under-The-Hood-Learning-112854551165759"&gt;Facebook&lt;/a&gt;, &lt;a href="https://twitter.com/UTHlearning"&gt;Twitter&lt;/a&gt;, or &lt;a href="https://www.instagram.com/underthehoodlearning/"&gt;Instagram&lt;/a&gt; pages so that you receive a notification every time I publish a new article. I'd suggest you subscribe to my blog, but it's not set up yet.😁 Anyway, you get the idea.&lt;/p&gt;

&lt;p&gt;Use the &lt;strong&gt;Observer&lt;/strong&gt; pattern when:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Changes to the state of one object require changing other objects, and the actual set of objects that are to be updated based on the state change is unknown beforehand or changes dynamically. For example, you created a custom button class, and you want to let the clients hook some custom code to your button so that it fires whenever a user presses the button. You can add the subscription mechanism to your button class, letting the clients hook up their custom code via custom subscriber classes.&lt;/li&gt;
&lt;li&gt;Some objects in your app must &lt;strong&gt;&lt;em&gt;observe&lt;/em&gt;&lt;/strong&gt; others, but only for a limited time or in specific cases. The observer list is dynamic, so subscribers can join or leave the list whenever they need to.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  What is the Observer pattern?
&lt;/h2&gt;

&lt;p&gt;The &lt;strong&gt;Observer&lt;/strong&gt; pattern consists of an &lt;strong&gt;&lt;em&gt;observable/subject/publisher&lt;/em&gt;&lt;/strong&gt; and an &lt;strong&gt;&lt;em&gt;observer/subscriber.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Observable/Subject/Publisher&lt;/strong&gt; is an object/class that maintains a list of observers/subscribers that it needs to notify when it is updated. It will also need to provide a subscription mechanism to allow the observers to subscribe or unsubscribe from its event streams. In reality, this mechanism consists of:

&lt;ol&gt;
&lt;li&gt;
&lt;code&gt;observers&lt;/code&gt;: This class property holds an array of observers.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;addObserver()&lt;/code&gt;: This method adds an observer to the &lt;code&gt;observers&lt;/code&gt; array&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;removeObserver()&lt;/code&gt;: This method removes an observer from the &lt;code&gt;observers&lt;/code&gt; array&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;notify()&lt;/code&gt;: This method notifies all observers that a change has happened.&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Observer/Subscriber&lt;/strong&gt; is any object/class that wants to subscribe/listen to changes in the _ &lt;strong&gt;publisher&lt;/strong&gt; _ by implementing an &lt;code&gt;update()&lt;/code&gt; method that will be called by the _ &lt;strong&gt;publisher's&lt;/strong&gt; _ &lt;code&gt;notify()&lt;/code&gt; method.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  How to implement the Observer pattern?
&lt;/h2&gt;

&lt;p&gt;In real-world applications, there might be several different subscriber classes/objects subscribing to the same publisher class. So, we wouldn't want to couple the publisher to all of those subscriber classes. That's why it's crucial that all subscribers implement the same &lt;strong&gt;&lt;em&gt;interface&lt;/em&gt;&lt;/strong&gt; and that the publisher communicates with them only through that interface. However, since we will be using Vanilla JS to keep things simple, we don't have access to &lt;strong&gt;&lt;em&gt;interfaces.&lt;/em&gt;&lt;/strong&gt; We can create &lt;strong&gt;&lt;em&gt;parent classes&lt;/em&gt;&lt;/strong&gt; from which we can extend. Specifically, the &lt;code&gt;Observable&lt;/code&gt; and &lt;code&gt;Observer&lt;/code&gt; parent classes will have those properties and methods required in order to implement the observer pattern.&lt;/p&gt;

&lt;p&gt;Building up from our previous example of the MVC architectural pattern in the previous blog post, we will now implement the &lt;strong&gt;Observer&lt;/strong&gt; pattern in order to achieve the &lt;strong&gt;&lt;em&gt;unidirectional data flow.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Create the &lt;code&gt;Observable&lt;/code&gt; parent class with the &lt;code&gt;addObserver()&lt;/code&gt; and &lt;code&gt;removeObserver()&lt;/code&gt;, and &lt;code&gt;notify()&lt;/code&gt; methods.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Observable {
   constructor() {
     this.observers = [];
   }

   // Add an observer to this.observers.
   addObserver(observer) {
     this.observers.push(observer);
   }

   // Remove an observer from this.observers.
   removeObserver(observer) {
     const removeIndex = this.observers.findIndex((obs) =&amp;gt; {
       return observer === obs;
     });

     if (removeIndex !== -1) {
       this.observers = this.observers.slice(removeIndex, 1);
     }
   }

   // Loops over this.observers and calls the update method on each observer.
   // The state object will call this method everytime it is updated.
   notify(data) {
     if (this.observers.length &amp;gt; 0) {
       this.observers.forEach((observer) =&amp;gt; observer.update(data));
     }
   }
}

export default Observable;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Create the &lt;code&gt;Observer&lt;/code&gt; parent class. At a bare minimum, it should include the &lt;code&gt;update()&lt;/code&gt; method.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Observer {
   // Gets called by the Subject::notify method.
   update() {}
 }

export default Observer;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Update the &lt;code&gt;HeadingModel&lt;/code&gt; class to have it extend the &lt;code&gt;Observable&lt;/code&gt; parent class.
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--IQGLUWJD--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res-4.cloudinary.com/under-the-hood-learning/image/upload/q_auto/v1/blog_images/2021-11-22-05_36_32-Computed-Diff---Diff-Checker.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--IQGLUWJD--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res-4.cloudinary.com/under-the-hood-learning/image/upload/q_auto/v1/blog_images/2021-11-22-05_36_32-Computed-Diff---Diff-Checker.png" alt="Observer Pattern with Vanilla JS" width="880" height="195"&gt;&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import Observable from "./observable";

class HeadingModel extends Observable {
   constructor() {
     super();
     this.heading = "Hello";
   }
}

export { HeadingModel };
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Update the &lt;code&gt;HeadingView&lt;/code&gt; class to have it extends the &lt;code&gt;Observer&lt;/code&gt; parent class. We will need to implement the &lt;code&gt;update()&lt;/code&gt; method that is required by the parent class and is called each time the &lt;code&gt;notify()&lt;/code&gt; method in the &lt;code&gt;Observable&lt;/code&gt; class is called. We will also need to register the &lt;code&gt;HeadingView&lt;/code&gt; as an _ &lt;strong&gt;observer&lt;/strong&gt; _ of the &lt;code&gt;HeadingModel&lt;/code&gt; _ &lt;strong&gt;observable&lt;/strong&gt; _ via the &lt;code&gt;addObserver()&lt;/code&gt; method.
&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--RnwNW7kM--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res-1.cloudinary.com/under-the-hood-learning/image/upload/q_auto/v1/blog_images/2021-11-22-05_38_54-Computed-Diff---Diff-Checker.png" alt="Observer Pattern with Vanilla JS" width="880" height="298"&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import Observer from "./observer";

class HeadingView extends Observer {
   constructor(controller) {
     super();
     this.controller = controller;
     this.heading = document.getElementById("heading");
     this.heading.innerText = controller.modelHeading;
     this.heading.addEventListener("click", controller);
     this.controller.model.addObserver(this);
   }

   update(model) {
     this.heading.innerText = model.heading;
   }
}

export { HeadingView };
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Finally, we need to update our controller's &lt;code&gt;clickHandler()&lt;/code&gt; method to call the &lt;code&gt;HeadingModel&lt;/code&gt;'s &lt;code&gt;notify()&lt;/code&gt; method each time the event is emitted instead of changing the &lt;code&gt;innerText&lt;/code&gt; through the controller.
&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--kwCO2i4M--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res-3.cloudinary.com/under-the-hood-learning/image/upload/q_auto/v1/blog_images/2021-11-22-05_44_02-Computed-Diff---Diff-Checker.png" alt="Observer Pattern with Vanilla JS" width="880" height="443"&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class HeadingController {
   constructor(model) {
     this.model = model;
   }

   //EVENTLISTENER INTERFACE
   handleEvent(e) {
     e.stopPropagation();
     switch (e.type) {
       case "click":
         this.clickHandler(e.target);
         break;
       default:
         console.log(e.target);
     }
   }

   get modelHeading() {
     return this.model.heading;
   }

   //CHANGE THE MODEL
   clickHandler(target) {
     this.model.heading = "World";
     this.model.notify(this.model);
   }
}

export { HeadingController };
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Our &lt;code&gt;main()&lt;/code&gt; function should still work as is.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Photo Credits
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;&lt;a href="https://www.freepik.com/photos/social-media"&gt;Social media photo created by jordy_pp - www.freepik.com&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;

</description>
      <category>designpattern</category>
      <category>generalconcepts</category>
    </item>
    <item>
      <title>MVC Architectural Design Pattern With Vanilla JS</title>
      <dc:creator>Thanh Truong</dc:creator>
      <pubDate>Wed, 05 Jan 2022 11:15:42 +0000</pubDate>
      <link>https://dev.to/thanhtr99270163/mvc-architectural-design-pattern-with-vanilla-js-3lfa</link>
      <guid>https://dev.to/thanhtr99270163/mvc-architectural-design-pattern-with-vanilla-js-3lfa</guid>
      <description>&lt;p&gt;Most people assume that the meaning of &lt;strong&gt;MVC (Model-View-Controller)&lt;/strong&gt; is static, but that's simply not true. MVC is not a well-defined concept, so do not assume it to be one in conversations. Instead, treat it more like a &lt;strong&gt;&lt;em&gt;buzzword&lt;/em&gt;&lt;/strong&gt; like "cloud".😉 MVC takes on a slightly different meaning depending on the specific context. Without a context, it is only a "fuzzy" concept in general.&lt;/p&gt;

&lt;p&gt;MVC is one of the most well-known architectural patterns and is the basis of many JavaScript frameworks (such as &lt;strong&gt;Angular&lt;/strong&gt; ) and several server-rendered web frameworks (such as &lt;strong&gt;ASP.NET Core MVC&lt;/strong&gt; ) &lt;strong&gt;.&lt;/strong&gt; As suggested by the post title, in this article, we will discuss the &lt;strong&gt;MVC pattern&lt;/strong&gt; in the context of &lt;strong&gt;&lt;em&gt;client-side development using JavaScript&lt;/em&gt;&lt;/strong&gt;.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;In this article, we will:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;briefly explore the original meaning of the MVC pattern by looking at its history&lt;/li&gt;
&lt;li&gt;explore the meaning of the MVC pattern in the context of JavaScript frontend development&lt;/li&gt;
&lt;li&gt;implement the MVC architectural pattern using only Vanilla JS on the frontend to gain a deep understanding and hands-on experience with this design pattern&lt;/li&gt;
&lt;/ul&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  History of MVC
&lt;/h2&gt;

&lt;p&gt;The MVC pattern was invented by &lt;strong&gt;Trygve Reenskaug&lt;/strong&gt; while he was a visiting scientist at the &lt;strong&gt;Smalltalk&lt;/strong&gt; group at the &lt;strong&gt;Xerox Palo Alto Research Center (PARC).&lt;/strong&gt; He wrote his first paper on MVC in 1978. The MVC pattern was invented long before the first web browser and was first implemented as part of the &lt;strong&gt;Smalltalk-80&lt;/strong&gt; class library. It was originally used as an architectural pattern for creating &lt;strong&gt;&lt;em&gt;graphical user interfaces (GUIs).&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The original meaning of the &lt;strong&gt;Model-View-Controller&lt;/strong&gt; pattern was very different than the meaning associated with the pattern today. In the context of a GUI,  the Model View Controller pattern was interpreted as follows:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Model:&lt;/strong&gt; A particular piece of data represented by an application, &lt;em&gt;e.g. weather station temperature reading.&lt;/em&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;View:&lt;/strong&gt; One representation of data from the model. The same model might have multiple views associated with it. The views are associated with a particular model through the &lt;strong&gt;Observer&lt;/strong&gt; relationship. For example, a temperature reading might be represented by both a label and a bar chart.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Controller:&lt;/strong&gt; Collects user inputs and modifies the model, &lt;em&gt;e.g. the controller might collect mouse click events and update the model.&lt;/em&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The primary benefit of this original version of the MVC pattern is a &lt;strong&gt;&lt;em&gt;Separated Presentation,&lt;/em&gt;&lt;/strong&gt; which was defined by &lt;strong&gt;Martin Fowler&lt;/strong&gt; as:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;A pattern that is used to ensure that any code that manipulates presentation only manipulates representation, pushing all domain and data source logic into clearly separated areas of the program.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In this pattern, the &lt;strong&gt;view&lt;/strong&gt; is updated indirectly from the &lt;strong&gt;model&lt;/strong&gt; via event handling. The &lt;strong&gt;controller&lt;/strong&gt; does not interact directly with the &lt;strong&gt;view.&lt;/strong&gt; Instead, the &lt;strong&gt;controller&lt;/strong&gt; modifies the &lt;strong&gt;model,&lt;/strong&gt; and since the &lt;strong&gt;view&lt;/strong&gt; is observing the &lt;strong&gt;model,&lt;/strong&gt; the &lt;strong&gt;view&lt;/strong&gt; gets updated.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why MVC?
&lt;/h2&gt;

&lt;p&gt;To really appreciate the beauty of the MVC pattern, let's look at an example of code without MVC.&lt;/p&gt;

&lt;p&gt;The traditional server-rendered web pages consist of static HTML documents. Each time the user requests a page, the server returns a new HTML page with the state of the information on the server at that moment in time. Then, &lt;strong&gt;AJAX&lt;/strong&gt; came along allowing us to update page elements and send user requests back to the server without having to wait for the server. However, AJAX development and adoption also brought with it more complexity in our code that required some sort of code restructuring for separation of concern, modularity, and reusability.&lt;/p&gt;

&lt;p&gt;Consider the following example. We have a simple form with a single textbox to allow the user to enter their email address for account registration. We will need to set up some validation logic for our form. In this case, the &lt;strong&gt;&lt;em&gt;event handler&lt;/em&gt;&lt;/strong&gt; function for the &lt;strong&gt;Submit&lt;/strong&gt; button in the script loops through a predetermined list of fields and run through the validation logic for each of the fields based on the class name metadata. Go ahead and try to click &lt;strong&gt;Submit&lt;/strong&gt; without any email address entered. You should see an alert dialog pop up with the warning.👇&lt;/p&gt;

&lt;p&gt;Although this approach works, it isn't very flexible. What if we want to add fields or validate a different form on another page. We would have to duplicate most of this functionality for each new field we add. Also, what if our validation logic is much more complicated than this, &lt;em&gt;e.g. a field is required only if another field is completed?&lt;/em&gt; You can probably imagine that our code would eventually grow out of control.😵&lt;/p&gt;

&lt;h2&gt;
  
  
  MVC with Vanilla JS
&lt;/h2&gt;

&lt;p&gt;Most of you are familiar with &lt;strong&gt;Single-Page Applications (SPA) MVC&lt;/strong&gt; frameworks such as &lt;strong&gt;Angular&lt;/strong&gt; that have become increasingly popular over the past few years. However, it's possible to implement the MVC architectural pattern on the front-end without using a framework or library. One of the benefits of this exercise is that it provides you with a solid understanding of how this pattern is implemented &lt;em&gt;"under the hood"&lt;/em&gt; so that when it's time for you to pick up a framework, you feel more comfortable understanding why it works the way it does. Without further ado, let's get started!😎&lt;/p&gt;

&lt;h3&gt;
  
  
  Build the View, Model, Controller
&lt;/h3&gt;

&lt;p&gt;Before we dive into the code, below is a demo of what we will be building for this example. Try clicking on the word "Hello" and observe how the text is dynamically updated to "World". Feel free to look at the files to familiarize yourself with the MVC structure.👇&lt;/p&gt;

&lt;p&gt;In the context of our frontend JS application, &lt;strong&gt;MVC&lt;/strong&gt; is an architecture with three layers:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Model:&lt;/strong&gt; is the container of our state and also performs business/domain logic.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;View:&lt;/strong&gt; is the visual representation of the models, &lt;em&gt;i.e. the output displayed to the user&lt;/em&gt; &lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Controller:&lt;/strong&gt; serves as the mediator between the &lt;strong&gt;model&lt;/strong&gt; and the &lt;strong&gt;view&lt;/strong&gt; and also stores some non-domain application states.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  The View
&lt;/h3&gt;

&lt;p&gt;For a browser-based, vanilla JS implementation, we have &lt;strong&gt;HTML&lt;/strong&gt; and the &lt;strong&gt;DOM&lt;/strong&gt; to worry about, so there will be two pieces to our &lt;strong&gt;view:&lt;/strong&gt; the &lt;strong&gt;HTML&lt;/strong&gt; itself and a &lt;strong&gt;View class&lt;/strong&gt; that encapsulates relevant &lt;strong&gt;DOM&lt;/strong&gt; selectors.&lt;/p&gt;

&lt;p&gt;In our example, the &lt;strong&gt;HTML&lt;/strong&gt; is very simple. It has the &lt;code&gt;&amp;lt;h1&amp;gt;&lt;/code&gt; element with the &lt;code&gt;id=heading&lt;/code&gt;, and references several scripts containing all of our code for the &lt;strong&gt;model, view,&lt;/strong&gt; and &lt;strong&gt;controller&lt;/strong&gt;. The initial value for the &lt;code&gt;&amp;lt;h1&amp;gt;&lt;/code&gt; element's &lt;code&gt;innerText&lt;/code&gt; will be set by the &lt;strong&gt;Controller&lt;/strong&gt; as you shall see later.&lt;/p&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;html&amp;gt;
  &amp;lt;head&amp;gt;
    &amp;lt;meta charset=”utf-8"&amp;gt;
    &amp;lt;meta name="”viewport”" content="”width" ="device-width”" /&amp;gt;
    &amp;lt;title&amp;gt;MVC Experiment&amp;lt;/title&amp;gt;
    &amp;lt;script src="./src/index.js"&amp;gt;&amp;lt;/script&amp;gt;
    &amp;lt;script src="./controllers/heading.controller.js"&amp;gt;&amp;lt;/script&amp;gt;
    &amp;lt;script src="./models/heading.model.js"&amp;gt;&amp;lt;/script&amp;gt;
    &amp;lt;script src="./views/heading.view.js"&amp;gt;&amp;lt;/script&amp;gt;
  &amp;lt;/head&amp;gt;

  &amp;lt;body&amp;gt;
    &amp;lt;h1 id="heading"&amp;gt;&amp;lt;/h1&amp;gt;
  &amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Our &lt;strong&gt;View&lt;/strong&gt; class is defined in the &lt;code&gt;heading.view.js&lt;/code&gt; file. We're passing a &lt;strong&gt;controller&lt;/strong&gt; into the constructor as a &lt;strong&gt;&lt;em&gt;dependency.&lt;/em&gt;&lt;/strong&gt; The controller will be listening for &lt;strong&gt;&lt;em&gt;events&lt;/em&gt;&lt;/strong&gt; on our relevant &lt;strong&gt;DOM nodes.&lt;/strong&gt; Here, we're interested in the &lt;code&gt;&amp;lt;h1&amp;gt;&lt;/code&gt; DOM node with the &lt;code&gt;id=heading&lt;/code&gt;. So, we populate the initial value for the &lt;code&gt;innerText&lt;/code&gt; of this &lt;code&gt;&amp;lt;h1&amp;gt;&lt;/code&gt; element to the initial state of the &lt;strong&gt;model,&lt;/strong&gt; and we do that via the &lt;strong&gt;controller.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We also register the &lt;strong&gt;&lt;em&gt;event handler&lt;/em&gt;&lt;/strong&gt; for the &lt;code&gt;&amp;lt;h1&amp;gt;&lt;/code&gt; element via the &lt;code&gt;addEventListener()&lt;/code&gt; method of the &lt;code&gt;EventTarget&lt;/code&gt; interface available in the &lt;strong&gt;Web API.&lt;/strong&gt; This interface can be implemented by any object that can receive events such as &lt;strong&gt;&lt;em&gt;element, document, window,&lt;/em&gt;&lt;/strong&gt; &lt;em&gt;etc.&lt;/em&gt; The &lt;code&gt;addEventListener()&lt;/code&gt; method sets up a function that will be called whenever the specified event is delivered by the target. In this case, we're passing in &lt;code&gt;click&lt;/code&gt; as the &lt;strong&gt;&lt;em&gt;event type&lt;/em&gt;&lt;/strong&gt; to listen for and the &lt;code&gt;controller&lt;/code&gt; itself as an object that implements the &lt;code&gt;EventListerner&lt;/code&gt; interface as you shall see in the section about the &lt;strong&gt;controller.&lt;/strong&gt;&lt;/p&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class HeadingView {
  constructor(controller) {
    this.controller = controller;
    this.heading = document.getElementById("heading");
    this.heading.innerText = controller.modelHeading;
    this.heading.addEventListener("click", controller);
  }
}

export { HeadingView };

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  The Model
&lt;/h3&gt;

&lt;p&gt;Our &lt;strong&gt;model&lt;/strong&gt; is defined in the &lt;code&gt;heading.model.js&lt;/code&gt; file. For this example, our &lt;strong&gt;model&lt;/strong&gt; will be very simple. It consists of a value for the heading, which is what we used to set our &lt;code&gt;&amp;lt;h1&amp;gt;&lt;/code&gt; element's &lt;code&gt;innerText&lt;/code&gt;. The model will be &lt;strong&gt;&lt;em&gt;injected&lt;/em&gt;&lt;/strong&gt; into the &lt;strong&gt;controller&lt;/strong&gt; so that the controller can manipulate the model as prompted by the &lt;strong&gt;view's events.&lt;/strong&gt;&lt;/p&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class HeadingModel {
  constructor() {
    this.heading = "Hello";
  }
}

export { HeadingModel };

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  The Controller
&lt;/h3&gt;

&lt;p&gt;As mentioned in the section about the &lt;strong&gt;View,&lt;/strong&gt; in order for the event handler to work as expected, the &lt;strong&gt;controller&lt;/strong&gt; must implement the &lt;code&gt;EventListener&lt;/code&gt; interface of the &lt;strong&gt;Web API.&lt;/strong&gt; This interface represents an object that can handle an event dispatched by an &lt;code&gt;EventTarget&lt;/code&gt; object (in this case, it's the &lt;code&gt;&amp;lt;h1&amp;gt;&lt;/code&gt; element). Any object that uses this interface (in this case, it's the &lt;strong&gt;controller&lt;/strong&gt; ) must implement the &lt;code&gt;handleEvent&lt;/code&gt; method, which is a function that is called whenever an event of the specified type occurs.&lt;/p&gt;

&lt;p&gt;Our &lt;strong&gt;controller&lt;/strong&gt; is defined in the &lt;code&gt;heading.controller.js&lt;/code&gt; file.&lt;/p&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class HeadingController {
  constructor(model) {
    this.model = model;
  }

  //EVENTLISTENER INTERFACE
  handleEvent(e) {
    e.stopPropagation();
    switch (e.type) {
      case "click":
        this.clickHandler(e.target);
        break;
      default:
        console.log(e.target);
    }
  }

  get modelHeading() {
    return this.model.heading;
  }

  //CHANGE THE MODEL
  clickHandler(target) {
    this.model.heading = "World";
    target.innerText = this.modelHeading;
  }
}

export { HeadingController };

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As shown in the code above, our &lt;strong&gt;controller&lt;/strong&gt; implements three methods:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;handleEvent&lt;/code&gt;: This method handles the &lt;code&gt;click&lt;/code&gt; event for the &lt;code&gt;&amp;lt;h1&amp;gt;&lt;/code&gt; element. If the event is &lt;code&gt;click&lt;/code&gt; then the &lt;code&gt;clickHandler()&lt;/code&gt; method is called.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;clickHandler&lt;/code&gt;: This method updates the &lt;strong&gt;model&lt;/strong&gt; as well as the &lt;code&gt;&amp;lt;h1&amp;gt;&lt;/code&gt; element's &lt;code&gt;innerText&lt;/code&gt; (represented as the &lt;code&gt;target&lt;/code&gt; parameter).&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;getModelHeading&lt;/code&gt;: This method is used to retrieve the current value of the heading property of the model. As mentioned in the &lt;strong&gt;View&lt;/strong&gt; section, we call this method to get the initial state of the model and assign the returned value to the &lt;code&gt;&amp;lt;h1&amp;gt;&lt;/code&gt; element.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Wiring Up Model-View-Controller
&lt;/h3&gt;

&lt;p&gt;Now that we have our &lt;strong&gt;model, view,&lt;/strong&gt; and &lt;strong&gt;controller&lt;/strong&gt; defined, we need to create and inject them in the correct order. We'll do that in the &lt;code&gt;index.js&lt;/code&gt; file.&lt;/p&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { HeadingModel } from "../models/heading.model";
import { HeadingController } from "../controllers/heading.controller";
import { HeadingView } from "../views/heading.view";

function main() {
  var model = new HeadingModel();
  var controller = new HeadingController(model);
  var view = new HeadingView(controller);
}

main();

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;strong&gt;model&lt;/strong&gt; is instantiated first, injected into the constructor for the &lt;strong&gt;controller,&lt;/strong&gt; and then the &lt;strong&gt;controller&lt;/strong&gt; is injected into the &lt;strong&gt;view.&lt;/strong&gt; Our &lt;strong&gt;model&lt;/strong&gt; does not know anything about the &lt;strong&gt;view&lt;/strong&gt; and vice versa. The &lt;strong&gt;controller&lt;/strong&gt; can interact with both since it's injected into the &lt;strong&gt;view,&lt;/strong&gt; and the &lt;strong&gt;model&lt;/strong&gt; is injected into the &lt;strong&gt;controller.&lt;/strong&gt; Finally, we invoke the &lt;code&gt;main()&lt;/code&gt; function and we should be able to click "Hello" to change it to "World".&lt;/p&gt;

&lt;p&gt;And there you have it. We've learned how to structure our code following the &lt;strong&gt;MVC&lt;/strong&gt; pattern using just Vanilla JS. Sure, we ended up with more code than what we had in the example without using MVC, but the idea is that this pattern can be expanded to make your code more modular and maintainable as your application grows in its complexity.&lt;/p&gt;

&lt;p&gt;We can stop here, but I think we can expand on these building blocks to make it even better by implementing the &lt;strong&gt;Observer&lt;/strong&gt; pattern to achieve a &lt;strong&gt;&lt;em&gt;unidirectional data flow&lt;/em&gt;&lt;/strong&gt; between the &lt;strong&gt;model&lt;/strong&gt; and the view. We can also add the ability to toggle between "Hello" and "World" by implementing the &lt;strong&gt;State&lt;/strong&gt; pattern. Going through these exercises would also help us learn about these two design patterns ( &lt;strong&gt;Observer&lt;/strong&gt; and &lt;strong&gt;State&lt;/strong&gt; patterns) in the most practical way. So let's do that in the next two articles.💪&lt;/p&gt;

</description>
      <category>designpattern</category>
      <category>generalconcepts</category>
    </item>
    <item>
      <title>AJAX Demystified - What Is AJAX?</title>
      <dc:creator>Thanh Truong</dc:creator>
      <pubDate>Wed, 29 Dec 2021 12:03:40 +0000</pubDate>
      <link>https://dev.to/thanhtr99270163/ajax-demystified-what-is-ajax-cj5</link>
      <guid>https://dev.to/thanhtr99270163/ajax-demystified-what-is-ajax-cj5</guid>
      <description>&lt;p&gt;In &lt;a href="https://dev.to/thanhtr99270163/ajax-demystified-why-do-we-need-ajax-388d"&gt;Part 1&lt;/a&gt; of this series, we laid the foundation for learning AJAX by digging deep into the history of web development at the time when AJAX was created. In this next part of the series, we will learn what &lt;strong&gt;AJAX&lt;/strong&gt; really is.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is AJAX?
&lt;/h2&gt;

&lt;p&gt;We learned from the previous blog post that AJAX was created to solve the problem with the "annoying" delay in the responsiveness of a sovereign web application. An AJAX application, therefore, eliminates the &lt;em&gt;start-stop-start-stop&lt;/em&gt; nature of interaction on the Web by implementing a collection of four technologies that complement one another: &lt;strong&gt;CSS,  DOM, JavaScript,&lt;/strong&gt; and &lt;strong&gt;XMLHttpRequest&lt;/strong&gt;.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;JavaScript (JS):&lt;/strong&gt; JavaScript is the glue that holds everything together in an AJAX application. JS is used to &lt;em&gt;define user workflow and business logic of the app, manipulates and refreshes the UI via the DOM to continually redraw and reorganize the data presented to the users based on user's interactions via mouse and keyboard event handling.&lt;/em&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;CSS:&lt;/strong&gt; In an AJAX application, the styling of a UI may be modified interactively through CSS.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;DOM:&lt;/strong&gt; The &lt;strong&gt;DOM&lt;/strong&gt; presents the structure of web pages as a set of programmable objects that can be manipulated with JS. Scripting the DOM allows an AJAX application to modify the UI on the fly, effectively redrawing parts of the page.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;XMLHttpRequest:&lt;/strong&gt; The XMLHttpRequest object allows data retrieval from the webserver asynchronously. The data format is typically &lt;strong&gt;XML&lt;/strong&gt; , but it works well with any text-based data. Nowadays,  the most common data format used for this is &lt;strong&gt;JSON.&lt;/strong&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;It's worth mentioning that three of the four technologies listed above ( &lt;strong&gt;CSS, DOM, JS&lt;/strong&gt; ) have been collectively referred to as &lt;strong&gt;Dynamic HTML (DHTML).&lt;/strong&gt;  DHTML offered the ability to create interactive UI for web pages. However, it never overcame the issue of the full-page refresh since without communicating with the server, there was only so much it could do. AJAX makes considerable use of DHTML, but with the ability to make asynchronous requests to the server, AJAX has a lot more to offer.&lt;/p&gt;

&lt;h2&gt;
  
  
  XMLHttpRequest
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;XMLHttpRequest&lt;/strong&gt; is a &lt;strong&gt;native API&lt;/strong&gt; in JS that encapsulates the logic of sending HTTP requests without having to refresh a loaded web page - _ &lt;strong&gt;AJAX request.&lt;/strong&gt; _ Even though developers rarely use XMLHttpRequest directly now, it's still the building block that works underneath many popular HTTP request modules such as &lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch"&gt;Fetch&lt;/a&gt; and &lt;a href="https://github.com/axios/axios"&gt;Axios&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The complete lifecycle of loading a document using XMLHttpRequest is as follows: _instantiate the XMLHttpRequest object, tell it to load a document, and then monitor that load process asynchronously using callback handlers.  _&lt;/p&gt;

&lt;p&gt;Now that you understand the high-level concept of AJAX, let's jump into some codes.👩‍💻 Let's try to implement AJAX using Vanilla JS. Why would we want to do that if there are several frameworks out there that have out-of-the-box AJAX technology? It's because we want to learn &lt;em&gt;"under the hood"&lt;/em&gt;, remember?😉&lt;/p&gt;

&lt;h2&gt;
  
  
  AJAX using Vanilla JS
&lt;/h2&gt;

&lt;p&gt;We will be implementing AJAX using Vanilla JS to build a simple web application as shown below. When the &lt;strong&gt;Retrieve&lt;/strong&gt; button is clicked, a "Hello World!" message returned by the backend server via an AJAX call is displayed right below the button without a page refresh. Try it for yourself!👇&lt;/p&gt;

&lt;p&gt;A simple AJAX implementation takes four steps:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Create an instance of the &lt;code&gt;XMLHttpRequest&lt;/code&gt; (aka &lt;code&gt;XHR&lt;/code&gt;) object&lt;/li&gt;
&lt;li&gt;Use the &lt;code&gt;open()&lt;/code&gt; method of the &lt;code&gt;XHR&lt;/code&gt; to specify what kind of data you want&lt;/li&gt;
&lt;li&gt;Create a function to process the response&lt;/li&gt;
&lt;li&gt;Use the XHR's &lt;code&gt;send()&lt;/code&gt; method to send the request&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Now, let's look at some code. For this simple demo, we have a simple backend web server written in &lt;strong&gt;Node.js&lt;/strong&gt; to process AJAX requests. For the UI on the frontend, we have a simple HTML and a script for the &lt;strong&gt;Retrieve&lt;/strong&gt; button's event handling.&lt;/p&gt;

&lt;h3&gt;
  
  
  Node.js Backend Web Server
&lt;/h3&gt;

&lt;p&gt;The code for our &lt;strong&gt;Node.js&lt;/strong&gt; web server is defined in the &lt;code&gt;index.js&lt;/code&gt; file located in the root directory.&lt;/p&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var http = require("http");
var fs = require("fs");

function render(path, contentType, fn) {
  fs.readFile(__dirname + "/" + path, "utf-8", function (err, str) {
    fn(err, str, contentType);
  });
}

//create a server object:
http
  .createServer(function (req, res) {
    var httpHandler = function (err, str, contentType) {
      if (err) {
        console.log(err);
        res.writeHead(500, { "Content-Type": "text/plain" });
        res.end("An error has occured: " + err.message);
      } else {
        res.writeHead(200, { "Content-Type": contentType });
        res.end(str);
      }
    };
    if (req.url.indexOf("/scripts/") &amp;gt;= 0) {
      console.log("Serving ajax.js");
      render(req.url.slice(1), "application/javascript", httpHandler);
    } else if (
      req.headers["x-requested-with"] === "XMLHttpRequest" &amp;amp;&amp;amp;
      req.headers["x-vanillaajaxwithoutjquery-version"] === "1.0"
    ) {
      console.log("Processing AJAX request");
      res.writeHead(200, { "Content-Type": "application/json" });
      res.end(JSON.stringify({ message: "Hello World!" }));
    } else {
      console.log("Serving index.html");
      render("views/index.html", "text/html", httpHandler);
    }
  })
  .listen(8080); //the server object listens on port 8080

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, we're using the &lt;a href="https://nodejs.org/api/http.html"&gt;&lt;code&gt;http&lt;/code&gt; module&lt;/a&gt; to create an &lt;strong&gt;HTTP server.&lt;/strong&gt; For those of you that are not familiar with &lt;strong&gt;Node.js,&lt;/strong&gt; here is a brief explanation of the code.&lt;/p&gt;

&lt;p&gt;The server is listening on Port &lt;code&gt;8080&lt;/code&gt;. The callback function we pass to the &lt;code&gt;createServer()&lt;/code&gt; method is executed for each request that comes in. Whenever a new request is received, the &lt;code&gt;request&lt;/code&gt; event is called, providing two objects: a &lt;strong&gt;request&lt;/strong&gt; (an &lt;code&gt;http.IncomingMessage&lt;/code&gt; object) and a &lt;strong&gt;response&lt;/strong&gt; (an &lt;code&gt;http.ServerResponse&lt;/code&gt; object). The &lt;code&gt;request&lt;/code&gt; provides the request details through which we can access the request &lt;code&gt;headers&lt;/code&gt; and request &lt;code&gt;data&lt;/code&gt;. The &lt;code&gt;response&lt;/code&gt; is used to populate the data returning to the client.&lt;/p&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var http = require("http");

//create a server object:
http
  .createServer(function (req, res) {
    // callback to handle request is define here
  })
  .listen(8080); //the server object listens on port 8080

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's look at the callback function used to handle requests.&lt;/p&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if (req.url.indexOf("/scripts/") &amp;gt;= 0) {
  render(req.url.slice(1), "application/javascript", httpHandler);
} else if (
  req.headers["x-requested-with"] === "XMLHttpRequest" &amp;amp;&amp;amp;
  req.headers["x-vanillaajaxwithoutjquery-version"] === "1.0"
) {
  res.writeHead(200, { "Content-Type": "application/json" });
  res.end(JSON.stringify({ message: "Hello World!" }));
} else {
  render("views/index.html", "text/html", httpHandler);
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This block of code checks the request URL to determine how the app should respond.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;If the request came from the &lt;code&gt;scripts&lt;/code&gt; directory, then the appropriate file is served with the &lt;code&gt;application/javascript&lt;/code&gt; content type. &lt;/li&gt;
&lt;li&gt;Any request with &lt;code&gt;x-request-with&lt;/code&gt; headers set to &lt;code&gt;XMLHttpRequest&lt;/code&gt; indicates an &lt;strong&gt;AJAX&lt;/strong&gt; request. In this case, we simply return a "Hello World!" text message.&lt;/li&gt;
&lt;li&gt;If it's neither of the two cases above, then the &lt;code&gt;index.html&lt;/code&gt; file is served.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;We haven't discussed the &lt;code&gt;render()&lt;/code&gt; and &lt;code&gt;httpHandler()&lt;/code&gt; functions yet, so let's do that now.  The &lt;code&gt;render()&lt;/code&gt; function asynchronously reads the contents of the requested file. It accepts the &lt;code&gt;httpHandler()&lt;/code&gt; callback function, which is used to check for errors and write the content of the file to the response with the appropriate HTTP status code if everything looks good.&lt;/p&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function render(path, contentType, fn) {
  fs.readFile(__dirname + "/" + path, "utf-8", function (err, str) {
    fn(err, str, contentType);
  });
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&amp;lt;!--kg-card-end: markdown--&amp;gt;&amp;lt;!--kg-card-begin: markdown--&amp;gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var httpHandler = function (err, str, contentType) {
  if (err) {
    console.log(err);
    res.writeHead(500, { "Content-Type": "text/plain" });
    res.end("An error has occured: " + err.message);
  } else {
    res.writeHead(200, { "Content-Type": contentType });
    res.end(str);
  }
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Frontend UI Code
&lt;/h2&gt;

&lt;p&gt;Now, let's look at our frontend code, which contains the &lt;code&gt;/views/index.html&lt;/code&gt; file and the &lt;code&gt;/scripts/ajax.js&lt;/code&gt; script used for the button event handling. The &lt;code&gt;index.html&lt;/code&gt; is straightforward. It references the &lt;code&gt;ajax.js&lt;/code&gt; script which is called when the user clicks the &lt;strong&gt;Retrieve&lt;/strong&gt; button.&lt;/p&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html&amp;gt;
  &amp;lt;head&amp;gt;
    &amp;lt;meta charset="utf-8" /&amp;gt;
    &amp;lt;meta name="viewport" content="width=device-width" /&amp;gt;
    &amp;lt;title&amp;gt;Vanilla Ajax without jQuery&amp;lt;/title&amp;gt;
  &amp;lt;/head&amp;gt;
  &amp;lt;body&amp;gt;
    &amp;lt;h1&amp;gt;Vanilla Ajax without jQuery&amp;lt;/h1&amp;gt;
    &amp;lt;button id="retrieve" data-url="/"&amp;gt;Retrieve&amp;lt;/button&amp;gt;
    &amp;lt;p id="results"&amp;gt;&amp;lt;/p&amp;gt;
    &amp;lt;script src="/scripts/ajax.js" async&amp;gt;&amp;lt;/script&amp;gt;
  &amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;ajax.js&lt;/code&gt; script is where most of the AJAX magic happens.&lt;/p&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;(function () {
  var retrieve = document.getElementById("retrieve"),
    results = document.getElementById("results"),
    toReadyStateDescription = function (state) {
      switch (state) {
        case 0:
          return "UNSENT";
        case 1:
          return "OPENED";
        case 2:
          return "HEADERS_RECEIVED";
        case 3:
          return "LOADING";
        case 4:
          return "DONE";
        default:
          return "";
      }
    };
  retrieve.addEventListener("click", function (e) {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
      console.log(
        "Inside the onreadystatechange event with readyState: " +
          toReadyStateDescription(xhr.readyState)
      );
      if (xhr.readyState === 4 &amp;amp;&amp;amp; xhr.status === 200) {
        if (xhr.responseType === "json") {
          results.innerHTML = xhr.response.message;
        } else {
          results.innerHTML = JSON.parse(xhr.responseText).message;
        }
      }
    };
    xhr.open("GET", e.target.dataset.url, true);
    xhr.responseType = "json";
    xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
    xhr.setRequestHeader("x-vanillaAjaxWithoutjQuery-version", "1.0");
    xhr.send();
  });
})();

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We followed the five steps to implement AJAX described in the previous sections:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Create an &lt;code&gt;xhr&lt;/code&gt; instance of the &lt;code&gt;XMLHttpRequest&lt;/code&gt; object using the XMLHttpRequest() constructor.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Use the &lt;code&gt;open()&lt;/code&gt; method of the &lt;code&gt;XMLHttpRequest&lt;/code&gt; object to specify the kind of data being requested. It takes three arguments:&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Create a callback function to process the response. &lt;code&gt;XHR&lt;/code&gt; has two properties used to indicate a response from the server:&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Finally, all we're left to do is send the request. But before we do that, we need to make sure we set the _ &lt;strong&gt;request headers&lt;/strong&gt; _ accordingly to indicate that our request is indeed an AJAX request.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Tie it all together
&lt;/h2&gt;

&lt;p&gt;Let's tit it all together - &lt;em&gt;frontend and backend.&lt;/em&gt; When we start the server by running &lt;code&gt;npm run start&lt;/code&gt;, the server returns the rendered &lt;code&gt;index.html&lt;/code&gt; page to the browser. Since the &lt;code&gt;index.html&lt;/code&gt; file references the &lt;code&gt;ajax.js&lt;/code&gt; script, the browser issues another request to the server to get this file. Finally, when the user clicks the &lt;strong&gt;Retrieve&lt;/strong&gt; button, the server returns the "Hello World!" message. This workflow can be observed via the server's terminal logger as shown below.&lt;/p&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Serving index.html
Serving ajax.js
Processing AJAX request

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  AJAX Implementations
&lt;/h2&gt;

&lt;p&gt;Below are some examples of AJAX implementations for your references:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Auto-suggestion:&lt;/strong&gt; Almost all search engines nowadays have this feature implemented. However, it's not limited to just search engines. In fact, it can be used in any text box in web forms.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Infinite scrolling:&lt;/strong&gt; Infinite scrolling is also implemented using AJAX. As the user scrolls downwards, more contents are fetched from the server and displayed on the page.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Self-Updating Stock Ticker:&lt;/strong&gt; Most trading sites have the stock tickers updated with the latest rates on the market automatically without reloading the entire page.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Form Validation:&lt;/strong&gt; For example, when a user enters an email address to sign up for an account, the user's input is sent to the database to check if it's an existing account. Depending on the server's response, the user is either allowed to proceed to the next step or an error is displayed on the screen. This whole process can be done asynchronously without reloading the whole page.&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>designpattern</category>
      <category>javascript</category>
    </item>
    <item>
      <title>AJAX Demystified - Why Do We Need AJAX?</title>
      <dc:creator>Thanh Truong</dc:creator>
      <pubDate>Wed, 22 Dec 2021 10:59:55 +0000</pubDate>
      <link>https://dev.to/thanhtr99270163/ajax-demystified-why-do-we-need-ajax-388d</link>
      <guid>https://dev.to/thanhtr99270163/ajax-demystified-why-do-we-need-ajax-388d</guid>
      <description>&lt;p&gt;This two-part series came into existence after I started the &lt;a href="https://www.underthehoodlearning.com/tag/"&gt;JavaScript Client-side Frameworks&lt;/a&gt; series. While I was researching materials for my posts, I can't tell you how many times I came across the &lt;strong&gt;AJAX&lt;/strong&gt; acronym. A quick Google search gave me some confirmations that I somewhat understand what AJAX does, but the more I dug, the more I realized that it's way more complicated than I thought, yet it's one of the building blocks in all JS frameworks. I was quickly convinced that understanding AJAX is fundamental to our understanding of modern JS frameworks. In this first part of this series, we will explore why we need AJAX in the first place.&lt;/p&gt;

&lt;p&gt;First off, don't let the cover image fool you. Yes, we're talking about AJAX - the technology, not Ajax - the Greek hero.😜&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Asynchronous JavaScript and XML (AJAX)&lt;/strong&gt; is a collection of interrelated web development techniques - we can think of AJAX as &lt;strong&gt;&lt;em&gt;design patterns&lt;/em&gt;&lt;/strong&gt; - that are used for &lt;strong&gt;asynchronous&lt;/strong&gt; web applications. AJAX allows web pages to send and receive data asynchronously in the background, without blocking the user from interacting with the web page while the request is being processed by the backend server.&lt;/p&gt;

&lt;p&gt;The classic web app model was built around the notion of pages. A document is displayed to the user, containing lists of links and form elements that allow them to drill down to further documents. Most user actions in the interface trigger an HTTP request back to a web server. The server does some processing before returning a new HTML page to the client. While the server is doing its thing, the user has to wait. This server-side web architecture models the transition between pages as state transition diagrams and the site itself as a collection of pages.&lt;/p&gt;

&lt;p&gt;It may be hard to comprehend the disadvantages of such an approach in traditional web app development since we are so used to the fast and responsive web apps as we know them today. So you will have to think of this in the context of how the Internet was being used in the years 2000's.&lt;/p&gt;

&lt;p&gt;Before we get into the &lt;strong&gt;WHY&lt;/strong&gt; behind &lt;strong&gt;AJAX,&lt;/strong&gt; there are a few concepts that we need to understand first. So, let's cover these prerequisites.&lt;/p&gt;

&lt;h2&gt;
  
  
  Sovereign vs. Transient Applications
&lt;/h2&gt;

&lt;p&gt;Software usability expert Alan Cooper has written about usage patterns and defines four distinct categories of software we use in our daily life: &lt;strong&gt;sovereign, transient, daemonic,&lt;/strong&gt; and &lt;strong&gt;parasitic.&lt;/strong&gt; For the purpose of this article, we will only focus on the first two usage modes: &lt;strong&gt;sovereign&lt;/strong&gt; and &lt;strong&gt;transient.&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Transient Applications&lt;/strong&gt;
A transient application might be used every day, but only in short bursts and usually as a secondary activity. When users are using these applications, they have already stepped out of their regular flow of work, and so a certain amount of clunkiness is acceptable. A calculator is a transient application, which is a type of helper program that is used for a specific task and then quickly closed again.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Sovereign Applications&lt;/strong&gt;
A sovereign application, in contrast, must cope with the user's full attention for several hours at a time. A good interface for a sovereign application must support the users _ &lt;strong&gt;invisibly&lt;/strong&gt; _, without breaking their concentration on the task at hand. &lt;strong&gt;Microsoft Word, Excel,&lt;/strong&gt; and &lt;strong&gt;Photoshop&lt;/strong&gt; are all examples of sovereign applications.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Why is this relevant to AJAX anyway?&lt;/strong&gt; 🤔 Valid question!😜 It's quite relevant, actually.&lt;/p&gt;

&lt;p&gt;In the late 90s to early 2000s, the classic and dominant &lt;strong&gt;&lt;em&gt;page-based web pages&lt;/em&gt;&lt;/strong&gt; were only good enough for _ &lt;strong&gt;transient&lt;/strong&gt; _ use. The browser itself is a _ &lt;strong&gt;sovereign&lt;/strong&gt; _ application that is typically used for hours on end, but the web pages were mostly _ &lt;strong&gt;transient&lt;/strong&gt; _ in their nature. In the early days of the Internet, users typically visited a specific website to check the weather, news, other information and then left. Desktop applications were dominant at the time when it comes to more sophisticated software that was created to solve business problems.&lt;/p&gt;

&lt;p&gt;_ &lt;strong&gt;"Why couldn't we convert existing desktop applications into web applications instead?"&lt;/strong&gt; _ is the next logical question one may ask.🤔 As a matter of fact, that was on web developers' wish list. One of the advantages of web applications is that it allows &lt;strong&gt;collaboration&lt;/strong&gt; , &lt;em&gt;i.e. resource sharing between team members&lt;/em&gt;, and &lt;strong&gt;flexibility&lt;/strong&gt; , &lt;em&gt;i.e. users can access applications from any computer with a browser and not have to worry about data backup.&lt;/em&gt; But to get there, there were a few challenges that needed to be solved first.&lt;/p&gt;

&lt;p&gt;The challenges lie in the way users interact with existing desktop applications, which were mostly _ &lt;strong&gt;sovereign applications.&lt;/strong&gt; _ With the traditional server-rendered web pages, When a user visits a web page, there is normally a small lag between when a button or a link is clicked &lt;em&gt;(I'll explain where this lag in time is coming from in the next section)&lt;/em&gt; because a round trip to the server is needed, and the whole page needs to be redrawn.&lt;/p&gt;

&lt;p&gt;If it's a typical weather site, the small lag doesn't bother the user much since the task itself - &lt;em&gt;checking the weather forecast&lt;/em&gt; - is a &lt;strong&gt;&lt;em&gt;transient&lt;/em&gt;&lt;/strong&gt; task that the user doesn't have to endure for a long period of time. However, if it's an application that is typically used for a few hours at a time, &lt;em&gt;i.e. a&lt;/em&gt; &lt;strong&gt;&lt;em&gt;sovereign application.&lt;/em&gt;&lt;/strong&gt; , it would drive the user nuts. How would you feel if there was a half of a second lag in &lt;strong&gt;Microsoft Word&lt;/strong&gt; every time you press a button?😫 It would get extremely frustrating, wouldn't it? So until this problem was solved, web developers back then accepted their fate and designed their websites to be used as &lt;strong&gt;&lt;em&gt;transient applications&lt;/em&gt;&lt;/strong&gt; instead.&lt;/p&gt;

&lt;p&gt;Now that you understand the challenges that web developers were trying to solve. Before we move on to how AJAX delivers the solution, let's first try to explore where the time lag is coming from.&lt;/p&gt;

&lt;h2&gt;
  
  
  Local vs. Remote Procedure Calls
&lt;/h2&gt;

&lt;p&gt;Why did desktop applications have the _ &lt;strong&gt;richness&lt;/strong&gt; _ and _ &lt;strong&gt;responsiveness&lt;/strong&gt; _ that seemed to lack in the classic web applications? In order to understand where the time lag presented in a typical web application is coming from, we need to understand the differences between &lt;strong&gt;local&lt;/strong&gt; and &lt;strong&gt;remote procedure calls.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In _ &lt;strong&gt;local procedure calls&lt;/strong&gt; _, when a _ &lt;strong&gt;non-networked&lt;/strong&gt; _ piece of code is compiled or interpreted, the various methods and functions are coded as instructions stored in the same _ &lt;strong&gt;local memory&lt;/strong&gt; _ as the _ &lt;strong&gt;data&lt;/strong&gt; _ on which the _ &lt;strong&gt;methods&lt;/strong&gt; _ operate. Thus, passing data to a method and returning a result is pretty straightforward. Local procedures are widely used in desktop applications since the logic and data model are both executed in a _ &lt;strong&gt;closed environment&lt;/strong&gt; _. Let's use an &lt;strong&gt;Excel&lt;/strong&gt; desktop application as an example, a spreadsheet sits on its own little pile of data, stored locally in memory and on the local file system.&lt;/p&gt;

&lt;p&gt;In contrast with a typical web page, in which a web browser has to contact the webserver sitting somewhere else &lt;em&gt;(could be on the other side of the world)&lt;/em&gt; to request the pages that the user is trying to access. In _ &lt;strong&gt;remote procedure calls&lt;/strong&gt; _, a lot of computation is going on "under the hood" at both ends of a network connection in order to send and receive data:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Encode and serialize (convert into a linear set of bytes) the request from the caller.&lt;/li&gt;
&lt;li&gt;Pass the serialized data to the &lt;strong&gt;HTTP&lt;/strong&gt; application protocol&lt;/li&gt;
&lt;li&gt;The data packet is then sent across the physical transport (cable, wireless connection, etc.)&lt;/li&gt;
&lt;li&gt;The remote machine receives the data and starts decoding and deserializing it before executing the requested procedure on the received data.&lt;/li&gt;
&lt;li&gt;The response is then encoded, serialized before sending over the wire back to the caller.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Network Latency
&lt;/h2&gt;

&lt;p&gt;The grand vision of the Internet age is that all computers in the world interconnect as one very large computing resource. The idea was that _ &lt;strong&gt;remote&lt;/strong&gt; _ and _ &lt;strong&gt;local procedure calls&lt;/strong&gt; _ become indistinguishable, and issuers of the calls are no longer even aware of which physical machines they are working on. Unfortunately, communications over a network are expensive as remote and local procedures are not the same thing at all. As mentioned in the section above, communications over a network are slow and unreliable.&lt;/p&gt;

&lt;p&gt;So, making a call over a network will never be as efficient as calling a local method in memory. I used to think that the physical journey along the wire is the most time-consuming process, but it's actually the computations under the hood that slow things down. Furthermore, the unreliability of the network, which is why lost packets of information need to be resent, only makes the matter worse. This delay, which is referred to as _ &lt;strong&gt;network latency&lt;/strong&gt; _, is a common cause of delayed responsiveness between users' initiated actions and the page's responses.&lt;/p&gt;

&lt;h2&gt;
  
  
  HTTP
&lt;/h2&gt;

&lt;p&gt;As mentioned above, the &lt;strong&gt;HTTP protocol&lt;/strong&gt; is used to transport serialized data between the requester (browser) and the server.&lt;/p&gt;

&lt;p&gt;Modern JavaScript provides a number of ways to send &lt;strong&gt;HTTP requests&lt;/strong&gt; to remote servers. An HTTP request consists of a request by the browser, followed by a response from the server. An HTTP request is mostly composed of &lt;strong&gt;headers&lt;/strong&gt; , with the &lt;strong&gt;body&lt;/strong&gt; containing some data or parameters. Think of the headers as lines of an address written on an envelope and the body as the letter inside. The headers simply instruct the receiving party what to do with the letter contents. The &lt;strong&gt;response&lt;/strong&gt; typically contains the HTML markup for the returning page.&lt;/p&gt;

&lt;h2&gt;
  
  
  Asynchronous Requests
&lt;/h2&gt;

&lt;p&gt;As mentioned above, _ &lt;strong&gt;network latency&lt;/strong&gt; _ is inherent in _ &lt;strong&gt;remote procedure calls&lt;/strong&gt; _ and is the common cause of delayed responsiveness in web applications. In other words, we can't get rid of network latency. &lt;strong&gt;&lt;em&gt;So how are we going to solve this problem then?&lt;/em&gt;&lt;/strong&gt; 🤔&lt;/p&gt;

&lt;p&gt;There was only one sane solution to the network latency problem: _ &lt;strong&gt;we must try to make the UI responses independent of network activity.&lt;/strong&gt; _ But &lt;strong&gt;&lt;em&gt;HOW&lt;/em&gt;&lt;/strong&gt;?🤔&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Asynchronous remote event handling&lt;/strong&gt; comes to the rescue.🦸‍♂️ Fortunately, although a half a second delay, &lt;em&gt;so to speak&lt;/em&gt;, each time the user clicks a button is not acceptable, a slight holding response to acknowledge the receipt of a request is often sufficient, as long as it is timely. Using an example from our physical world, when you make your morning coffee, you don't stand next to the coffee machine staring at it while waiting for it to brew, do you? So why are we doing that in our computer world?😉&lt;/p&gt;

&lt;p&gt;Seriously, there should be no reason for the user to stare at the computer screen waiting for the newly requested web page to arrive. Let's use the Amazon website as an example. After adding a new item to my shopping basket, I should be able to browse other items on the site while the total cost for all items in my basket is being calculated, right?&lt;/p&gt;

&lt;p&gt;With any UI, it's a well-established practice to spawn an &lt;strong&gt;asynchronous thread&lt;/strong&gt; to handle any lengthy piece of computation and let it run in the background while the user gets on with other tasks. The user is necessarily blocked while that thread is _ &lt;strong&gt;launched,&lt;/strong&gt; _ but this can be done in an acceptably short span of time. So, _ &lt;strong&gt;asynchronous remote event handling&lt;/strong&gt; _ is not a new concept, and so far, it seems like we've already figured out the solution to our problem, which is _ &lt;strong&gt;asynchronously processing remote calls&lt;/strong&gt; _. So what is so revolutionary about &lt;strong&gt;AJAX&lt;/strong&gt; anyway?&lt;/p&gt;

&lt;p&gt;Here is the catch!😜 Unfortunately for us web developers, &lt;strong&gt;HTTP&lt;/strong&gt; is a request-response protocol. That is, the client issues a request for a document, and the server responds, either by delivering the document, saying that it can't find it, offering an alternative location, or telling the client to use its cached copy, etc. In other words, a request-response protocol is &lt;strong&gt;&lt;em&gt;one-way.&lt;/em&gt;&lt;/strong&gt; The client can make contact with the server, but the server cannot initiate communication with the client. As a matter of fact, the server doesn't remember the client from one request to the next, and it shouldn't have to. Okay, so where is the catch again?😁&lt;/p&gt;

&lt;p&gt;So we said earlier that the key feature of our &lt;strong&gt;&lt;em&gt;asynchronous callback&lt;/em&gt;&lt;/strong&gt; solution is that the client gets notified &lt;strong&gt;twice:&lt;/strong&gt; once when the thread is spawned and again when the thread is completed. How can the server notify the client that it has completed the request if HTTP protocol is a _ &lt;strong&gt;one-way communication?&lt;/strong&gt; _ Aha!😜 But don't worry! That's what AJAX is for.😎&lt;/p&gt;

&lt;p&gt;Now that you understand AJAX's mission, we are now ready to learn what AJAX really is. See you in the next part of this series! 👋&lt;/p&gt;

</description>
      <category>designpattern</category>
      <category>javascript</category>
    </item>
    <item>
      <title>Asynchronous JavaScript (JS) Demystified</title>
      <dc:creator>Thanh Truong</dc:creator>
      <pubDate>Wed, 15 Dec 2021 11:13:13 +0000</pubDate>
      <link>https://dev.to/thanhtr99270163/asynchronous-javascript-js-demystified-3b8j</link>
      <guid>https://dev.to/thanhtr99270163/asynchronous-javascript-js-demystified-3b8j</guid>
      <description>&lt;p&gt;In this article, we will look under the hood to understand how asynchronous function is executed in JavaScript. We will explore concepts such as &lt;strong&gt;call stack, event loop,&lt;/strong&gt; and &lt;strong&gt;message queue&lt;/strong&gt; which are the key players behind asynchronous JS.&lt;/p&gt;

&lt;p&gt;JavaScript is a single-threaded programming language - _a language with one single &lt;strong&gt;call stack&lt;/strong&gt; and a single &lt;strong&gt;memory heap.&lt;/strong&gt; _ What it means is that the &lt;strong&gt;JavaScript engine&lt;/strong&gt; can only process one statement at a time in a single thread.&lt;/p&gt;

&lt;p&gt;Although single-threaded languages offer some levels of simplicity since developers don't have to worry about concurrency, applications coded in single-threaded programming languages face challenges with long operations (such as network access) blocking the main thread. For example, imagine what it feels like when the web page is unresponsive even just for a few seconds after you clicked a button to request some data from the API. It would be annoying, would it?😉&lt;/p&gt;

&lt;p&gt;That's where &lt;strong&gt;asynchronous JavaScript&lt;/strong&gt; comes into play. Using asynchronous JavaScript &lt;strong&gt;(callbacks, promises, async/await),&lt;/strong&gt; we can perform long network requests without blocking the main thread. But &lt;strong&gt;how?&lt;/strong&gt; 🤔&lt;/p&gt;

&lt;p&gt;Before we dive into &lt;strong&gt;asynchronous JS,&lt;/strong&gt; let's first try to understand how its counterpart, &lt;strong&gt;synchronous code,&lt;/strong&gt; gets executed inside the JS engine by looking at some simple codes.&lt;/p&gt;

&lt;h2&gt;
  
  
  How is synchronous code executed by the JS engine?
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const second = () =&amp;gt; {
  console.log('Hello there!');
}
const first = () =&amp;gt; {
  console.log('Hi there!');
  second();
  console.log('The End');
}
first();

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When the above code executes, the following outputs are logged in the console:&lt;/p&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Hi there!
Hello there!
The End

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To understand how the above code executes inside the JS engine, we have to understand the concept of &lt;strong&gt;&lt;em&gt;execution context&lt;/em&gt;&lt;/strong&gt; and the &lt;strong&gt;&lt;em&gt;call stack&lt;/em&gt;&lt;/strong&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Execution Context
&lt;/h3&gt;

&lt;p&gt;An &lt;strong&gt;execution context&lt;/strong&gt; is an abstract concept of an &lt;strong&gt;&lt;em&gt;environment&lt;/em&gt;&lt;/strong&gt; where the JS code is evaluated and executed. Whenever any code is run in JS, it's run inside an execution context.&lt;/p&gt;

&lt;p&gt;By _ &lt;strong&gt;environment,&lt;/strong&gt; _ we mean the value of &lt;code&gt;this&lt;/code&gt;, &lt;code&gt;variables&lt;/code&gt;, &lt;code&gt;objects&lt;/code&gt;, and &lt;code&gt;functions&lt;/code&gt; JS code has access to at a particular time.&lt;/p&gt;

&lt;p&gt;There are three types of execution context in JS:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Global execution context:&lt;/strong&gt;
This is the default execution context in which JS code starts its execution when the file first loads in the browser. All global code, &lt;em&gt;i.e. code that is not inside any function or object,&lt;/em&gt; is executed inside the global execution context. &lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Functional execution context:&lt;/strong&gt;
This is the execution context created by the JS engine whenever it finds a function call. Each function has its own execution context. Functional execution context has access to all the code of the global execution context but not vice versa.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Eval:&lt;/strong&gt;
Execution context inside &lt;code&gt;eval&lt;/code&gt; function.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Call Stack
&lt;/h3&gt;

&lt;p&gt;The call stack is a stack with a &lt;strong&gt;Last In First Out (LIFO)&lt;/strong&gt; structure, which is used to store all the execution context created during code execution. The LIFO structure implies that the items can be added or removed from the top of the stack only. Let's use the example code above to illustrate what this really means.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--sMx-hQkQ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res-4.cloudinary.com/under-the-hood-learning/image/upload/q_auto/v1/blog_images/Async-JS.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--sMx-hQkQ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res-4.cloudinary.com/under-the-hood-learning/image/upload/q_auto/v1/blog_images/Async-JS.png" alt="Asynchronous JavaScript (JS) Demystified" width="880" height="1132"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;When the code is executed, a global execution context is created represented by the &lt;code&gt;main()&lt;/code&gt; method and pushed to the top of the call stack.&lt;/li&gt;
&lt;li&gt;When a call to &lt;code&gt;first()&lt;/code&gt; is encountered, it's pushed to the top of the stack.&lt;/li&gt;
&lt;li&gt;Since &lt;code&gt;console.log('Hi there!')&lt;/code&gt; is called from within the &lt;code&gt;first()&lt;/code&gt; method, it's pushed to the top of the stack, and the "Hi there!" message is logged to the console. Once finished, it's popped off the stack. &lt;/li&gt;
&lt;li&gt;Next, we call &lt;code&gt;second()&lt;/code&gt;, so the &lt;code&gt;second()&lt;/code&gt; function is pushed to the top of the stack.&lt;/li&gt;
&lt;li&gt;Since &lt;code&gt;second()&lt;/code&gt; calls &lt;code&gt;console.log('Hello there!')&lt;/code&gt;, it's pushed to the top of the stack, and the "Hello there!" message is logged to the console. Once finished, it's popped off the stack followed by the &lt;code&gt;second()&lt;/code&gt; function.&lt;/li&gt;
&lt;li&gt;The last thing that remains in the &lt;code&gt;first()&lt;/code&gt; function is the call to &lt;code&gt;console.log('The End')&lt;/code&gt;, so it's pushed to the top of the stack, and the "The End" message is logged to the console. Once finished, it's popped off the stack.&lt;/li&gt;
&lt;li&gt;Since there is nothing left inside the &lt;code&gt;first()&lt;/code&gt; function, it's popped off the stack followed by &lt;code&gt;main()&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  How is asynchronous code executed by the JS engine?
&lt;/h2&gt;

&lt;p&gt;Now that we know how synchronous code executes, let's look at how &lt;strong&gt;asynchronous code&lt;/strong&gt; executes.&lt;/p&gt;

&lt;p&gt;As mentioned above, network requests take time. Depending upon the situation, the server might take some time to process the request while blocking the main thread making the web page unresponsive. The solution to this problem is to use &lt;strong&gt;asynchronous callbacks&lt;/strong&gt; to make out code non-blocking. An example of an asynchronous callback function is shown below. Here, we used the &lt;code&gt;setTimeout&lt;/code&gt; method (available from the &lt;strong&gt;Web API&lt;/strong&gt; in browsers) to simulate a network request.&lt;/p&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const networkRequest = () =&amp;gt; {
  setTimeout(() =&amp;gt; {
    console.log('Async Code');
  }, 2000);
};

console.log('Hello World');
networkRequest();
console.log('The End');

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When the above code executes, the following messages are logged to the console:&lt;/p&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Hello World
The End
Async Code

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So, it seems that the call to &lt;code&gt;networkRequest()&lt;/code&gt; did not block our thread after all. But we said earlier, that JavaScript is a single-threaded language, so is that even possible?🤔 To understand how this code is executed, we need to understand a few more concepts such as &lt;strong&gt;event loop&lt;/strong&gt; and &lt;strong&gt;message/task queue.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;JavaScript has a concurrency model based on &lt;strong&gt;event loop,&lt;/strong&gt; which is responsible for &lt;em&gt;executing the code, collecting and processing events, and executing queue sub-tasks.&lt;/em&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Message Queue
&lt;/h3&gt;

&lt;p&gt;A JavaScript runtime uses a &lt;strong&gt;message queue,&lt;/strong&gt; which is a list of messages to be processed. Each message has an associated _ &lt;strong&gt;function&lt;/strong&gt; _ that gets called in order to handle the message.&lt;/p&gt;

&lt;p&gt;At some point during the &lt;strong&gt;event loop&lt;/strong&gt; when the call stack is empty &lt;strong&gt;,&lt;/strong&gt; the runtime starts handling the messages on the queue, starting with the oldest one. The message is removed from the queue and its corresponding function is called. This process repeats every time the &lt;strong&gt;event loop&lt;/strong&gt; detects that the call stack is empty indicating the next message in the queue (if available) can be processed.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;ES6&lt;/strong&gt; introduced the concept of &lt;strong&gt;job queue/micro-task queue,&lt;/strong&gt; which is used by &lt;strong&gt;Promises&lt;/strong&gt; in JS. The difference between the message queue and the job queue is that &lt;strong&gt;&lt;em&gt;the job queue has a higher priority than the message queue,&lt;/em&gt;&lt;/strong&gt; which means that promise jobs inside the job queue/micro-task queue will be executed before the callbacks inside the message queue.&lt;/p&gt;

&lt;h3&gt;
  
  
  Event Loop
&lt;/h3&gt;

&lt;p&gt;The &lt;strong&gt;event loop&lt;/strong&gt; got its name because of how it's usually implemented, which usually resembles:&lt;/p&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;while (queue.waitForMessage()) {
  queue.processNextMessage()
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The job of the event loop is to look into the call stack and determine if the call stack is empty or not. If it's empty, it looks into the &lt;strong&gt;message queue&lt;/strong&gt; to see if there's any pending callback waiting to be executed. Each message is processed completely before another message is processed.&lt;/p&gt;

&lt;p&gt;In web browsers, messages are added anytime an event occurs and there is an event listener attached to it.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;The &lt;strong&gt;event loop, message queue,&lt;/strong&gt; and &lt;strong&gt;web APIs&lt;/strong&gt; are not part of the JS engine. They are part of the browser's JS runtime environment &lt;strong&gt;Node.js&lt;/strong&gt; runtime environment in the case of Nodejs.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;With all of that out of the way, let's revisit our example of asynchronous callback and dissect it.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;When the above code loads in the browser, the &lt;code&gt;console.log('Hello World')&lt;/code&gt; is pushed to the stack, and the "Hello World" message is logged to the console. Once finished, it's popped off the stack.
&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--m7F3juSc--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res-1.cloudinary.com/under-the-hood-learning/image/upload/q_auto/v1/blog_images/1.png" alt="Asynchronous JavaScript (JS) Demystified" width="880" height="495"&gt;
&lt;/li&gt;
&lt;li&gt;Next, the &lt;code&gt;networkRequest()&lt;/code&gt; is called, so it's pushed to the top of the stack.
Since &lt;code&gt;setTimeout()&lt;/code&gt; is called from within &lt;code&gt;networkRequest()&lt;/code&gt;, it's pushed to the top of the stack. This method takes two arguments: a time in &lt;code&gt;ms&lt;/code&gt; and a callback function that is to be executed once the timer expires. The &lt;code&gt;setTimeout()&lt;/code&gt; method starts a timer of 2s in the web API environment.
&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--XznWlNfe--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res-2.cloudinary.com/under-the-hood-learning/image/upload/q_auto/v1/blog_images/2.png" alt="Asynchronous JavaScript (JS) Demystified" width="880" height="495"&gt;
&lt;/li&gt;
&lt;li&gt;At this point, the &lt;code&gt;setTimeout()&lt;/code&gt; has finished and is popped off the stack.
Next, the &lt;code&gt;console.log('The End')&lt;/code&gt; is pushed to the stack, and the "The End" message is logged to the console, after which the function is popped off the stack.
&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--UtvOHvuf--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res-5.cloudinary.com/under-the-hood-learning/image/upload/q_auto/v1/blog_images/3.png" alt="Asynchronous JavaScript (JS) Demystified" width="880" height="495"&gt;
&lt;/li&gt;
&lt;li&gt;Meanwhile, the timer has expired, and the callback is pushed to the message queue. At this point, since the call stack is empty, the event loop pushes the callback in the queue to the top of the call stack. Since the callback calls &lt;code&gt;console.log('Async Code')&lt;/code&gt;, it's pushed to the top of the stack. The "Async Code" message is logged to the console before it's popped off the stack.
&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--V9FOrbL9--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res-5.cloudinary.com/under-the-hood-learning/image/upload/q_auto/v1/blog_images/4.png" alt="Asynchronous JavaScript (JS) Demystified" width="880" height="495"&gt;
&lt;/li&gt;
&lt;li&gt;Since the callback is finished, it's also popped off the stack and the program finally finishes.
&amp;lt;!--kg-card-end: markdown--&amp;gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;That's it. I hope that by now, asynchronous function call in JS is no longer a mystery to you.😉&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>generalconcepts</category>
    </item>
    <item>
      <title>Tutorial: Build a JAMStack Blog with Gatsby and Ghost - Part 1</title>
      <dc:creator>Thanh Truong</dc:creator>
      <pubDate>Wed, 08 Dec 2021 10:55:08 +0000</pubDate>
      <link>https://dev.to/thanhtr99270163/tutorial-build-a-jamstack-blog-with-gatsby-and-ghost-part-1-51if</link>
      <guid>https://dev.to/thanhtr99270163/tutorial-build-a-jamstack-blog-with-gatsby-and-ghost-part-1-51if</guid>
      <description>&lt;p&gt;In this first part of the tutorial, we will spin up our blog in a local development to get it ready for deployment into the cloud in the next part of the tutorial.&lt;/p&gt;

&lt;h2&gt;
  
  
  1. Set up Gatsby Ghost Starter project
&lt;/h2&gt;

&lt;p&gt;We will build a custom front-end for our site with &lt;strong&gt;Gatsby.js&lt;/strong&gt;. Gatsby.js can be defined as a &lt;strong&gt;static site generator&lt;/strong&gt; that uses &lt;strong&gt;React.js&lt;/strong&gt; (for the client-side) and &lt;strong&gt;GraphQL&lt;/strong&gt; (to access data) to build reliable and faster website. Static site generators can be defined as software applications that generates HTML pages from templates or components.&lt;/p&gt;

&lt;p&gt;One of the best ways to start a new Gatsby site is with a &lt;strong&gt;Gatsby Starter&lt;/strong&gt;. Gatsby starter libraries are open-source Gatby sites maintained by Gatsby and the Gatsby community. Ranging from minimal boilerplate to full proofs-of-concept, Gatsby starters enable you to dive into your nect Gatsby project faster.&lt;br&gt;&lt;br&gt;
 &lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--YnHAuWig--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res-3.cloudinary.com/hvb67jtvl/image/upload/q_auto/v1/ghost-blog-images/admin-api-gatsby-diagram.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--YnHAuWig--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res-3.cloudinary.com/hvb67jtvl/image/upload/q_auto/v1/ghost-blog-images/admin-api-gatsby-diagram.png" alt="Tutorial: Build a JAMStack Blog with Gatsby and Ghost - Part 1" width="880" height="460"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The official Gatsby Starter Ghost project comes preconfigured with the &lt;code&gt;gatsby-source-ghost&lt;/code&gt; plugin, which pulls data from the Ghost Public API (more details on that later), and a clone of the default Ghost template so that we can get started quickly. &lt;strong&gt;Gatsby plugins&lt;/strong&gt; are Node.js packages that implement Gatsby APIs. Plugins allow you to modularize your site customization into site-specific functionality. For example, you can use plugins to &lt;em&gt;add external data or content (CMS, REST API, etc.) to your Gatsby GraphQL data, transform data from other format (Markdown, YAML, etc.) to JSON objects, add third-party services (Google Analytics) to your site, and much more.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Now that we got some of the high-level concepts covered, let's go ahead and clone the &lt;code&gt;gatsby-starter-ghost&lt;/code&gt; project from GitHub.&lt;/p&gt;



&lt;p&gt;First, you will need to create a private repository in your GitHub account. Once that's done, we can start cloning the project.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;git clone https://github.com/TryGhost/gatsby-starter-ghost.git

cd gatsby-starter-ghost

# Install all packages
yarn install

# Start gatsby project
yarn dev

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once ready, we should be able to access our site at &lt;a href="http://localhost:8000/"&gt;http://localhost:8000/&lt;/a&gt;.&lt;br&gt;&lt;br&gt;
 &lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--4OWMu_BH--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res-3.cloudinary.com/hvb67jtvl/image/upload/q_auto/v1/ghost-blog-images/2021-10-17-08_56_31-Ghost-Gatsby-Starter---Ghost---Gatsby.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--4OWMu_BH--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res-3.cloudinary.com/hvb67jtvl/image/upload/q_auto/v1/ghost-blog-images/2021-10-17-08_56_31-Ghost-Gatsby-Starter---Ghost---Gatsby.png" alt="Tutorial: Build a JAMStack Blog with Gatsby and Ghost - Part 1" width="880" height="751"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;By default, our starter project is fetching data from the public Ghost Blog API @ &lt;a href="https://gatsby.ghost.io/"&gt;https://gatsby.ghost.io/&lt;/a&gt;. The API endpoints configuration is the &lt;code&gt;.ghost.json&lt;/code&gt; file located at the project root directory. Currently, our &lt;code&gt;.ghost.json&lt;/code&gt; looks like the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//.ghost.json

{
  "development": {
    "apiUrl": "https://ghost-v4-server.herokuapp.com",
    "contentApiKey": "8b7f72f624963ccbe84f28777a"
  },
  "production": {
    "apiUrl": "https://ghost-v4-server.herokuapp.com",
    "contentApiKey": "8b7f72f624963ccbe84f28777a"
  }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What we need to do next is set up our own Ghost CMS API where we will be storing all of our site content including images, videos, blog posts, etc.&lt;/p&gt;

&lt;h2&gt;
  
  
  2. Set up Ghost Content API
&lt;/h2&gt;

&lt;p&gt;First, we will set up a local instance of our Ghost API just for our own understanding of how it works. Since our goal is to eventually deploy our Ghost API to &lt;strong&gt;Heroku&lt;/strong&gt; , we will not be using this local instance for deployment. More details on that later.&lt;/p&gt;




&lt;h3&gt;
  
  
  Install Ghost locally
&lt;/h3&gt;

&lt;p&gt;Install Ghost CLI:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;yarn global add ghost-cli

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Create a new directory and initialize a new Ghost project:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mkdir ghost-admin &amp;amp;&amp;amp; cd ghost-admin
ghost install local

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once finished installing, you should now have an instance of Ghost running locally at &lt;a href="http://localhost:2368/"&gt;http://localhost:2368/&lt;/a&gt;. You can verify that your Ghost instance is running by running the &lt;code&gt;ghost status&lt;/code&gt; command from your &lt;code&gt;ghost-admin&lt;/code&gt; project director. You should see the following:&lt;br&gt;&lt;br&gt;
 &lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--fPvuaB3e--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res-4.cloudinary.com/hvb67jtvl/image/upload/q_auto/v1/ghost-blog-images/2021-10-17-10_31_37-Command-Prompt---heroku---heroku--login---heroku.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--fPvuaB3e--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res-4.cloudinary.com/hvb67jtvl/image/upload/q_auto/v1/ghost-blog-images/2021-10-17-10_31_37-Command-Prompt---heroku---heroku--login---heroku.png" alt="Tutorial: Build a JAMStack Blog with Gatsby and Ghost - Part 1" width="880" height="179"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;NOTE: When Ghost is running, you should see NodeJS running in a separate Windows command, you will need to keep this open in order for Ghost to run. You can also use the &lt;code&gt;ghost start&lt;/code&gt; or &lt;code&gt;ghost stop&lt;/code&gt; commands to manually start and stop Ghost. Reference Ghost &lt;a href="https://ghost.org/docs/install/local/"&gt;documentation&lt;/a&gt; for more information.&lt;/p&gt;
&lt;/blockquote&gt;


&lt;h3&gt;
  
  
  Configure Gatsby to use the new local Ghost API instance
&lt;/h3&gt;

&lt;p&gt;To test your Ghost API, navigate to &lt;a href="http://localhost:2368/"&gt;http://localhost:2368/&lt;/a&gt;. You should see the default Casper theme that comes with every Ghost installation. Ghost ships with a default front-end theme layer built with Handlebars. However, based on its flexible architecture, it can also be used as a &lt;strong&gt;headless CMS&lt;/strong&gt; with third party front-end frameworks, which is exactly what we're going to do for our site. The image below demonstrates the architecture for our stack. We will be using Gatsby as the &lt;strong&gt;static site generator&lt;/strong&gt; and &lt;strong&gt;Ghost Admin&lt;/strong&gt; as the client app to allow us to manage our blog content.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--LI8QZER---/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res-1.cloudinary.com/hvb67jtvl/image/upload/q_auto/v1/ghost-blog-images/ghost-architecture.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--LI8QZER---/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res-1.cloudinary.com/hvb67jtvl/image/upload/q_auto/v1/ghost-blog-images/ghost-architecture.png" alt="Tutorial: Build a JAMStack Blog with Gatsby and Ghost - Part 1" width="880" height="587"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;To access the &lt;strong&gt;Ghost Admin&lt;/strong&gt; client, navigate to &lt;a href="http://localhost:2368/ghost"&gt;http://localhost:2368/ghost&lt;/a&gt;. Follow the instructions to create a user account.&lt;/p&gt;

&lt;p&gt;Under &lt;strong&gt;Intergration&lt;/strong&gt; → &lt;strong&gt;Custom Integrations&lt;/strong&gt; → &lt;strong&gt;Gatsby Content API&lt;/strong&gt; , copy and paste both the &lt;strong&gt;API URL&lt;/strong&gt; and &lt;strong&gt;Content API Key&lt;/strong&gt; into the &lt;code&gt;.ghost.json&lt;/code&gt; file in your Gatsby project. You only need to update the "development" config for now since we're still running the project locally. Your &lt;code&gt;.ghost.json&lt;/code&gt; file should now look like the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "development": {
    "apiUrl": "http://localhost:2368",
    "contentApiKey": "c16cb3fb2cd6f36dea2012564d"
  },
  "production": {
    "apiUrl": "https://gatsby.ghost.io",
    "contentApiKey": "9cc5c67c358edfdd81455149d0"
  }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Before we test the new API, let's create a new post from Ghost Admin and see if it will be updated on our front-end site.&lt;/p&gt;




&lt;h3&gt;
  
  
  Test the local Ghost API
&lt;/h3&gt;

&lt;p&gt;Create and publish a new post from within the Ghost Admin client. Refresh your Gatsby site at &lt;a href="http://localhost:8000/"&gt;http://localhost:8000/&lt;/a&gt; and you should see your new post on the home page. 🎉&lt;/p&gt;

&lt;p&gt;By now, you should have both the front-end and back-end of your blog running locally. In the next tutorial, we will deploy both the front-end and back-end to the Cloud. See you there! 👋&lt;/p&gt;




&lt;h3&gt;
  
  
  Photo Credits:
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://www.freepik.com/vectors/man"&gt;Man vector created by vectorjuice - www.freepik.com&lt;/a&gt;&lt;/p&gt;

</description>
      <category>jamstack</category>
      <category>tutorials</category>
    </item>
    <item>
      <title>How I Created My Blog Using JAMStack</title>
      <dc:creator>Thanh Truong</dc:creator>
      <pubDate>Wed, 01 Dec 2021 14:34:28 +0000</pubDate>
      <link>https://dev.to/thanhtr99270163/how-i-created-my-blog-using-jamstack-1lko</link>
      <guid>https://dev.to/thanhtr99270163/how-i-created-my-blog-using-jamstack-1lko</guid>
      <description>&lt;p&gt;In the first two articles of this series, we explored &lt;strong&gt;JAMStack&lt;/strong&gt; &lt;em&gt;(what it is, its components and architecture, available tools for JAMStack development, its pros and cons, and comparison between WordPress and JAMStack)&lt;/em&gt;. If you haven't read it yet, I highly suggest you give it a read first.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://www.underthehoodlearning.com/what-is-jamstack-and-whether-you-should-use-it-for-your-app/"&gt;What Is JAMStack And Whether You Should Use It For Your App?&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://dev.to/thanhtr99270163/jamstack-vs-wordpress-which-one-is-better-2c87"&gt;JAMStack vs. WordPress: Which One Is Better?&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For the remainder of this series, I'll walk you through the process of how I created my personal blog with JAMStack &lt;em&gt;- a modern web development practice&lt;/em&gt;. But before we jump into our first tutorial, let's review the entire process at the high level and some &lt;em&gt;"gotchas"&lt;/em&gt; and challenges I discovered along the way and how I overcame those challenges.😎&lt;/p&gt;

&lt;h2&gt;
  
  
  Why JAMStack?
&lt;/h2&gt;

&lt;p&gt;My decision to set up my own blog as well as my decision to use JAMStack came a long way. I originally started blogging on &lt;a href="https://dev.to/thanhtr99270163"&gt;DEV Community&lt;/a&gt;. DEV is really a great community, don't get me wrong, but I was in need of a blogging platform that would offer some amount of flexibility and customization of how my blog should look like. Also, I thought it would be great to start growing my personal "brand", and having your own blog with your own domain name would be a good starting point.&lt;/p&gt;

&lt;p&gt;So I set out to look for a way to cross-post content between my blog on DEV Community and my to-be-created blog with its own domain name. I quickly noticed that DEV actually has an extension that would allow you to generate a personal blog from your DEV Community posts using &lt;a href="https://www.stackbit.com/"&gt;Stackbit&lt;/a&gt;. Great! "This is exactly what I need", I said to myself. I then followed some tutorials trying to set up my own blog on Stackbit.👩‍💻&lt;/p&gt;

&lt;p&gt;However, I quickly ran into issues migrating my posts from DEV Community into Stackbit. I emailed Stackbit's support team and was told that they were aware of the issue and have been working on fixing it. Bummer!😞&lt;/p&gt;

&lt;p&gt;I could either wait until Stackbit fixes the issue or find another solution. I decided to find another solution simply because I just don't like the fact that I have to rely on someone else to fix the problem, and that's just the nature of using a &lt;strong&gt;&lt;em&gt;site builder&lt;/em&gt;&lt;/strong&gt;  like Stackbit, which is aimed toward less technical users.&lt;/p&gt;

&lt;p&gt;So my mission now is to find another solution, which I will explain in more detail in the next section. However, I think it's important to acknowledge the fact that my decision to use JAMStack as well as what tools to use to build my JAMStack app started with Stackbit and is heavily influenced by it. After all, I learned about &lt;strong&gt;Netlify, Gatsby,&lt;/strong&gt; and even &lt;strong&gt;Ghost CMS&lt;/strong&gt; from my initial attempt with Stackbit because it uses JAMStack.&lt;/p&gt;

&lt;h2&gt;
  
  
  JAMStack components recap
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--gpNV3U47--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res-2.cloudinary.com/under-the-hood-learning/image/upload/q_auto/v1/blog_images/10586.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--gpNV3U47--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res-2.cloudinary.com/under-the-hood-learning/image/upload/q_auto/v1/blog_images/10586.jpg" alt="How I Created My Blog Using JAMStack" width="880" height="587"&gt;&lt;/a&gt;&lt;br&gt;&lt;br&gt;
Let's quickly recap all the components of our JAMStack blog and the technologies that we will be using for each of the components.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Static site generator&lt;/strong&gt;&lt;br&gt;&lt;br&gt;
All websites, doesn't matter what they are, fundamentally consists of HTML, CSS, and JavaScript. It doesn't matter what tools or frameworks you use to create your website, the final result needs to be compiled into these file formats in order for the browser to understand and display on the screen. Our blog is no exception.&lt;br&gt;&lt;br&gt;
There are two sources of HTML for our blog: the &lt;strong&gt;static&lt;/strong&gt; HTML contents (site header, logo, layout, footer, etc.) and the &lt;strong&gt;dynamic&lt;/strong&gt; HTML contents from the actual blog posts. We need to somehow combine both of these &lt;strong&gt;&lt;em&gt;static&lt;/em&gt;&lt;/strong&gt; and &lt;strong&gt;&lt;em&gt;dynamic&lt;/em&gt;&lt;/strong&gt; HTML sources into a single HTML file at every single build of our app. &lt;strong&gt;Static site generator&lt;/strong&gt; to the rescue!🦸‍♂️&lt;br&gt;&lt;br&gt;
A &lt;strong&gt;&lt;em&gt;static site generator&lt;/em&gt;&lt;/strong&gt; is a software application that creates HTML pages from templates or components and a given content source during a &lt;strong&gt;&lt;em&gt;build&lt;/em&gt;&lt;/strong&gt; process. There are many static site generators available out there. We will be using &lt;a href="https://www.gatsbyjs.com/"&gt;Gatsby&lt;/a&gt; for our blog.&lt;br&gt;&lt;br&gt;
During a build, &lt;strong&gt;Gatsby&lt;/strong&gt; loads JSON data from &lt;strong&gt;GraphQL&lt;/strong&gt; and merges it with components to create HTML pages. These generated pages are then deployed to a web server. When the server receives a request from a browser, it responds with rendered HTML.&lt;br&gt;&lt;br&gt;
So the question that needs to be answered now is &lt;strong&gt;&lt;em&gt;where does the GraphQL data come from?&lt;/em&gt;&lt;/strong&gt;🤔. I'm glad you asked because that's exactly what we're going to explore in the next section.😉&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Content Management System (CMS)&lt;/strong&gt;&lt;br&gt;&lt;br&gt;
Dynamic contents for JAMStack sites &lt;em&gt;(in our case, these are our blog posts)&lt;/em&gt; can be controlled via a CMS, typically known as &lt;strong&gt;&lt;em&gt;headless CMS.&lt;/em&gt;&lt;/strong&gt; Once a change is made in CMS &lt;em&gt;(a post is published/added/edited/deleted)&lt;/em&gt;, a new build of our site will be triggered and deployed as static assets. Similar to static site generators, there are many options for CMS available out there, but we will be using &lt;a href="https://ghost.org/"&gt;Ghost CMS&lt;/a&gt; for our blog.&lt;br&gt;&lt;br&gt;
As mentioned above, after a change is made to either our &lt;strong&gt;&lt;em&gt;static HTML&lt;/em&gt;&lt;/strong&gt; from &lt;strong&gt;Gatsby&lt;/strong&gt; or to our &lt;strong&gt;&lt;em&gt;dynamic HTML&lt;/em&gt;&lt;/strong&gt; from &lt;strong&gt;Ghost CMS&lt;/strong&gt; , we will need to somehow trigger the deployment to the web server to rebuild and regenerate the HTML files. How are we going to do that?🤔 Again, glad you asked! Join me in the next section!😎&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Deployment&lt;/strong&gt;&lt;br&gt;&lt;br&gt;
The generated HTML pages need to be hosted on a web server somewhere in order to allow users from anywhere to access our blog. There are several services available, but we will be using &lt;a href="https://www.netlify.com/"&gt;Netlify&lt;/a&gt; for our blog.&lt;br&gt;&lt;br&gt;
I chose Netlify because it has an awesome &lt;a href="https://www.netlify.com/pricing/"&gt;free plan&lt;/a&gt; that comes with great features such as:&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Now that you understand all these components at a high level, I'll share with you some of the challenges that I encountered as I was setting up my blog.&lt;/p&gt;

&lt;h2&gt;
  
  
  Gatsby static site generator
&lt;/h2&gt;

&lt;p&gt;In order to get my site up and running as quickly as possible, I decided to use one of Gatsby's &lt;a href="https://www.gatsbyjs.com/starters"&gt;starter libraries&lt;/a&gt;. &lt;strong&gt;Starters&lt;/strong&gt; are open-source Gatsby sites maintained by Gatsby that enable users to dive into their next Gatsby project with minimum effort. Starters range from minimal boilerplate to full proof of concept. Since we will be using &lt;strong&gt;Ghost&lt;/strong&gt; as our content management system. It seems logical that the &lt;a href="https://www.gatsbyjs.com/starters/TryGhost/gatsby-starter-ghost/"&gt;gatsby-starter-ghost&lt;/a&gt; is the best option for us.&lt;/p&gt;

&lt;p&gt;Besides a few customizations to give the blog the look and feel of my personal brand, the following features were implemented/improved to suit my needs:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Added a &lt;a href="https://www.underthehoodlearning.com/tag/"&gt;Tags&lt;/a&gt; page that displays my posts grouped by their corresponding tags.&lt;/li&gt;
&lt;li&gt;Added &lt;strong&gt;Google Analytics&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;Added &lt;a href="https://www.algolia.com/"&gt;Algolia Search&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Added block code syntax highlight using &lt;a href="https://highlightjs.org/"&gt;highlight.js&lt;/a&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Ghost CMS
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Ghost&lt;/strong&gt; offers &lt;a href="https://ghost.org/pricing/"&gt;Ghost(Pro)&lt;/a&gt; &lt;em&gt;- a managed hosting service for Ghost&lt;/em&gt; that offers users the fastest way to get started on Ghost. It includes out-of-the-box features such as &lt;em&gt;custom domain, custom themes, server maintenance and backups, CDN, etc.&lt;/em&gt; However, since I was looking for a low-cost option, I opted for a &lt;a href="https://ghost.org/docs/install/"&gt;self-hosted instance&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Out of the box, Ghost comes with:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;A core JSON API&lt;/li&gt;
&lt;li&gt;An admin client app&lt;/li&gt;
&lt;li&gt;A front-end theme layer using &lt;strong&gt;Handlebars&lt;/strong&gt; templating languages&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;However, since I use Gatsby for the frontend theme layer, I had to modify a few things after installing Ghost. Ghost's Admin Client app has the page preview feature that only works if you use one of Ghost's themes. Therefore, I had to set up a proxy server with some URL redirect configuration in order to be able to preview my posts with my Gatsby theme from the Admin Client app. The page preview on the Branding setting page still doesn't work, but that didn't bother me much, so I didn't spend time fixing it. More on that later when we get to the tutorials.&lt;/p&gt;

&lt;h2&gt;
  
  
  Cloud hosting
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--ouce2HdB--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res-5.cloudinary.com/under-the-hood-learning/image/upload/q_auto/v1/blog_images/3040061.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--ouce2HdB--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res-5.cloudinary.com/under-the-hood-learning/image/upload/q_auto/v1/blog_images/3040061.jpg" alt="How I Created My Blog Using JAMStack" width="880" height="880"&gt;&lt;/a&gt;&lt;br&gt;&lt;br&gt;
As mentioned above, we will use &lt;strong&gt;Netlify&lt;/strong&gt; to manage automatic build and deployment of our site. Basically, we will connect Netlify to our GitHub repo where we store our Gatsby code and configure it so that every time a change is pushed to the remote repo, a build is triggered in Netlify. In addition to that, we will integrate Netlify's &lt;strong&gt;build hook&lt;/strong&gt; with Ghost so that every time a change is made in Ghost (you can configure what type of changes you want such as post added, post updated, global changes, etc.), a build in Netlify is automatically triggered.&lt;/p&gt;

&lt;p&gt;Unless you're planning on hosting your Ghost server on your local machine, which you can if you want, you will need to pick a cloud platform ( &lt;strong&gt;AWS, Azure, Heroku, Digital Ocean,&lt;/strong&gt; etc.) to host your server app. Since my goal is to come up with a low-cost solution, here is what I ended up using for my stack:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Use &lt;strong&gt;Heroku&lt;/strong&gt; to host my Ghost server, which is essentially a &lt;strong&gt;Node.js&lt;/strong&gt; app. I found &lt;a href="https://github.com/thelovekesh/ghost-v4-on-heroku/"&gt;this&lt;/a&gt; GitHub repo that can be used to deploy a Ghost server into Heroku with just a click of a button. However, this app is preconfigured to use &lt;a href="https://www.jawsdb.com/"&gt;JawsDB&lt;/a&gt; as the &lt;strong&gt;MySQL&lt;/strong&gt; database where all data for our posts are stored. JawsDB does have a &lt;strong&gt;free plan&lt;/strong&gt; , but it only comes with &lt;strong&gt;5MB&lt;/strong&gt; of storage. The next price tier is &lt;strong&gt;$10/month&lt;/strong&gt; for which you'll get &lt;strong&gt;1GB&lt;/strong&gt; of data. I needed to come up with a lower-cost option for my data storage.&lt;/li&gt;
&lt;li&gt;I ended up using &lt;strong&gt;AWS RDS&lt;/strong&gt; for my MySQL database. If you sign up for a free tier account with AWS, you're eligible for &lt;strong&gt;750 hours&lt;/strong&gt; of RDS instances and &lt;strong&gt;20GB&lt;/strong&gt; of storage. Even if after you have used up your free tier credits, the cost to host a MySQL database on Amazon RDS is still much lower compared to JawsDB. Therefore, I needed to modify the code in the GitHub repo to re-configure the add-ons. More on that later!&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;As mentioned above, in order to fix the site preview issue in Ghost, I had to create a proxy server, which is essentially a &lt;strong&gt;Node.js&lt;/strong&gt; app, which is also hosted on Heroku.&lt;/p&gt;

&lt;h2&gt;
  
  
  My blogging workflow
&lt;/h2&gt;

&lt;p&gt;With this setup, here is my typical workflow just so that you can understand what it looks like:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Edit site template&lt;/strong&gt;

&lt;ul&gt;
&lt;li&gt;Edit and test site locally&lt;/li&gt;
&lt;li&gt;Commit and push changes to GitHub&lt;/li&gt;
&lt;li&gt;Netlify automatically builds and deploys the site&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Publish new content&lt;/strong&gt;

&lt;ul&gt;
&lt;li&gt;Add/remove/edit posts locally and publish from the Ghost Admin Client app&lt;/li&gt;
&lt;li&gt;Netlify automatically builds and deploys the site based on change detection settings in Netlify's build hook. Below is an image, taken from Ghost's website, just to give you an idea of what the UI for the Admin Client app looks like.
&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--COK_ea6i--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res-5.cloudinary.com/under-the-hood-learning/image/upload/q_auto/v1/blog_images/post-list-1600.png" alt="How I Created My Blog Using JAMStack" width="880" height="500"&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;That's it. Sounds simple, huh?😎 Well, if you like what you hear and are still interested, join me in the next part of this series where I will be sharing tutorials on how I set up my site. See you there! 👋&lt;/p&gt;

&lt;h2&gt;
  
  
  Photo Credits:
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;&lt;a href="https://www.freepik.com/vectors/technology"&gt;Technology vector created by pch.vector - www.freepik.com&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.freepik.com/vectors/technology"&gt;Technology vector created by stories - www.freepik.com&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;

</description>
      <category>jamstack</category>
      <category>tutorials</category>
    </item>
    <item>
      <title>ASP.NET Core: What Is It?</title>
      <dc:creator>Thanh Truong</dc:creator>
      <pubDate>Wed, 24 Nov 2021 13:00:00 +0000</pubDate>
      <link>https://dev.to/thanhtr99270163/aspnet-core-what-is-it-11f0</link>
      <guid>https://dev.to/thanhtr99270163/aspnet-core-what-is-it-11f0</guid>
      <description>&lt;p&gt;In the &lt;a href="https://www.underthehoodlearning.com/what-really-is-the-net-framework/"&gt;first article&lt;/a&gt; of this series, we explored the high-level overview of the .NET platform. In this and probably the next few posts of this series, we will dive deep into the ASP.NET Core platform.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is ASP?
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;ASP&lt;/strong&gt; stands for &lt;strong&gt;Microsoft Active Server Pages&lt;/strong&gt; , which is Microsoft's first server-side script engine that enabled dynamically-generated web pages. At the high level, ASP is one of the several technologies for developing &lt;strong&gt;Internet Information Service (IIS)&lt;/strong&gt; Web applications.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;IIS&lt;/strong&gt; is a web server specific to the &lt;strong&gt;Microsoft .NET platform.&lt;/strong&gt; on the Windows OS. IIS can be used to create web content in a variety of formats: &lt;em&gt;static files, scripts, compiled DLLs, and compiled EXEs.&lt;/em&gt; The _ &lt;strong&gt;IIS development technologies&lt;/strong&gt; _ simply provide a way to perform dynamic operations that eventually build HTML output that IIS sends in response to client requests.&lt;br&gt;&lt;br&gt;
In the context of IIS, a &lt;strong&gt;web server&lt;/strong&gt; is essentially a software that controls how web users access hosted files.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;ASP is now obsolete and replaced with ASP.NET.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is ASP.NET Core?
&lt;/h2&gt;

&lt;p&gt;Before we dive in, here is the picture of the entire .NET ecosystem that I used in the &lt;a href="https://www.underthehoodlearning.com/what-really-is-the-net-framework/"&gt;previous post&lt;/a&gt;. In this and future few articles, we will be focusing on the ASP.NET Core platform. If you are anything like me who find it confusing and convoluted with all the technical jargon floating around (.NET, .NET Core, ASP.NET, ASP.NET Core 😵), pictures speak a thousand words. 😉&lt;br&gt;&lt;br&gt;
 &lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--94dm_cu_--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res-3.cloudinary.com/under-the-hood-learning/image/upload/q_auto/v1/blog_images/20181002-.NET-Core-Focus.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--94dm_cu_--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res-3.cloudinary.com/under-the-hood-learning/image/upload/q_auto/v1/blog_images/20181002-.NET-Core-Focus.png" alt="ASP.NET Core: What Is It?" width="880" height="495"&gt;&lt;/a&gt;&lt;br&gt;&lt;br&gt;
As mentioned in the &lt;a href="https://www.underthehoodlearning.com/what-really-is-the-net-framework/"&gt;previous article&lt;/a&gt;, Microsoft created ASP.NET Core as a lightweight platform that runs on Windows, Linux, and macOS. .NET Core shares many of the same APIs as .NET Framework, except for it's smaller and only implements a subset of the features available in the .NET Framework.&lt;/p&gt;

&lt;p&gt;Fundamentally, an ASP.NET Core Web app is, at its core, a console app that reads and writes information to port. The .NET Core platform provides a base console application model that can be run cross-platform using the command line interface. Adding a web server library converts it into an ASP.NET Core web app. And this is exactly what Microsoft did as shown in the image below. Additional features, such as &lt;em&gt;configuration&lt;/em&gt; and &lt;em&gt;logging&lt;/em&gt; are added by way of additional libraries.&lt;br&gt;&lt;br&gt;
 &lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--meJ0a8TC--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res-2.cloudinary.com/under-the-hood-learning/image/upload/q_auto/v1/blog_images/NET-Core-Console1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--meJ0a8TC--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res-2.cloudinary.com/under-the-hood-learning/image/upload/q_auto/v1/blog_images/NET-Core-Console1.png" alt="ASP.NET Core: What Is It?" width="880" height="495"&gt;&lt;/a&gt;&lt;br&gt;&lt;br&gt;
Basically, we write a .NET Core console app that starts up an instance of an ASP.NET Core web server. By default, Microsoft provides Kestrel as the cross-platform web server. Our web application logic is run by Kestrel, and libraries are used to enable additional features as needed &lt;em&gt;(logging, HTML generation).&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  What type of applications can we build with ASP.NET Core?
&lt;/h2&gt;

&lt;p&gt;With &lt;strong&gt;.NET Core&lt;/strong&gt; , you can write code for &lt;em&gt;cross-platform ASP.NET Web apps, cross-platform console apps, cross-platform libraries and frameworks, and Universal Windows Platform (UWP) apps.&lt;/em&gt; But since we're only focusing on ASP.NET Core, let's see what type of web apps we can build using this framework.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Web UI&lt;/strong&gt;&lt;br&gt;&lt;br&gt;
ASP.NET Core is a complete UI framework. There are three general approaches to building modern web UI with ASP.NET Core:&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Web API&lt;/strong&gt;&lt;br&gt;&lt;br&gt;
ASP.NET Core supports creating RESTful services, also known as web APIs, using C#. To handle requests, a web API uses _ &lt;strong&gt;controllers&lt;/strong&gt; _ - &lt;em&gt;classes that derive from&lt;/em&gt; &lt;code&gt;ControllerBase&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Real-time apps&lt;/strong&gt;&lt;br&gt;&lt;br&gt;
ASP.NET Core &lt;strong&gt;SignalR&lt;/strong&gt; is an open-source library that simplifies adding real-time web functionality to apps. Real-time web functionality enables server-side code to push content to clients instantly &lt;em&gt;(gaming, social networks, voting, collaborative apps, maps, etc.).&lt;/em&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Remote Procedure Call (RPC)&lt;/strong&gt;&lt;br&gt;&lt;br&gt;
&lt;strong&gt;gRPC&lt;/strong&gt; , an open-source Remote Procedure Call framework, can be hosted on ASP.NET Core. The idea behind RPC is that a computer program can call and execute a procedure (subroutine or service) on a remote system just like it would call a local subroutine, but the network communication details are hidden from the user.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;In the next two articles, we will dive deep into all the components of a typical ASP.NET Core application using a simple &lt;strong&gt;web UI&lt;/strong&gt; application. See you there!👋&lt;/p&gt;

</description>
      <category>netframework</category>
    </item>
    <item>
      <title>JAMStack vs. WordPress: Which One Is Better?</title>
      <dc:creator>Thanh Truong</dc:creator>
      <pubDate>Wed, 17 Nov 2021 10:27:00 +0000</pubDate>
      <link>https://dev.to/thanhtr99270163/jamstack-vs-wordpress-which-one-is-better-2c87</link>
      <guid>https://dev.to/thanhtr99270163/jamstack-vs-wordpress-which-one-is-better-2c87</guid>
      <description>&lt;p&gt;In the &lt;a href="https://dev.to/thanhtr99270163/what-is-jamstack-and-whether-you-should-use-it-for-your-app-3dnf"&gt;previous blog post&lt;/a&gt;, we learned what JAMStack is, its components, available tools for building a JAMStack app, and its benefits and limitations.&lt;/p&gt;

&lt;p&gt;In this article, we will explore the core philosophy behind JAMStack architecture by comparing it to the well-known WordPress architecture.&lt;/p&gt;

&lt;h2&gt;
  
  
  How did JAMStack come about?
&lt;/h2&gt;

&lt;p&gt;Everything created was created to solve a problem. To understand how JAMStack comes into existence, we first need to understand what problems it was trying to solve.&lt;br&gt;&lt;br&gt;
Prior to JAMStack, WordPress ruled the world of content management. First released in 2004, WordPress has shifted from purely a blogging platform to a multi-purpose website creator that is supported by a huge ecosystem of themes and plugins. Since it's possible to get a WordPress site up and running inexpensively and with no coding knowledge, it has become the defacto choice for many website owners. However, being overloaded with add-ons, scripts, and a lot of other stuff results in some pain points such as &lt;em&gt;slow performance, higher cost, security concerns, and undesirable experiences for developers&lt;/em&gt;. As a result, developers have been looking for an alternative to solve these issues.&lt;br&gt;&lt;br&gt;
Then, JAMStack came along. JAMStack is all about fast and secure sites and apps delivered by pre-rendering files and serving them directly from a CDN, removing the requirement to manage or run web servers.&lt;/p&gt;

&lt;h2&gt;
  
  
  How does a WordPress website work?
&lt;/h2&gt;

&lt;p&gt;To understand the differences between WordPress and JAMStack architecture, we will use the analogy of news delivery.&lt;br&gt;&lt;br&gt;
Imagine for a second that the only way for people to know what's happening in the world is to go to the nearby news kiosk and ask to read the latest news.&lt;br&gt;&lt;br&gt;
The person selling newspapers at the kiosk has no ways to know the latest news, so he passes the request on the a back room full of telephone operators. When an operator becomes available, they will take the request and phone a long list of news agencies, ask for the latest news and then write the results as bullet points on a piece of paper.&lt;br&gt;&lt;br&gt;
The operator will then pass his rough notes on to a scribbler who will write the final copy to a beautiful sheet of paper, arrange them in a specific layout and add a few bits and pieces such as the kiosk branding and contact information. Finally, the attendant takes the finished paper and serves it to a happy customer.&lt;br&gt;&lt;br&gt;
The entire process repeats for every person that arrives at the kiosk. That is essentially how dynamic website works.&lt;br&gt;&lt;br&gt;
When a visitor gets to a website (the kiosk) expecting the latest content (the news), a _ &lt;strong&gt;server-side script&lt;/strong&gt; _ (the operators) will query one or multiple _ &lt;strong&gt;databases&lt;/strong&gt; _ (news agencies) to get the content. It then passes the results to a _ &lt;strong&gt;templating engine&lt;/strong&gt; _ (the scribbler) who wil format and arrange everything properly and generate an _ &lt;strong&gt;HTML&lt;/strong&gt; _ file (the finished newspaper) for the user to consume.&lt;br&gt;&lt;br&gt;
Fundamentally, dynamic websites like those created with WordPress are built for each visitor. Of course, you can cache the website, but the system is designed in a way that is complicated and cumbersome.&lt;/p&gt;

&lt;h2&gt;
  
  
  How does a JAMStack app work?
&lt;/h2&gt;

&lt;p&gt;A JAMStack site shifts the heavy load from the moment visitors request the content to change into content that is already there waiting for the visitors.&lt;br&gt;&lt;br&gt;
Going back to our kiosk analogy earlier, the new agencies would call the kiosk whenever something newsworthy happens. The kiosk operators and scribblers will compile, format, and style the stories and produce a finished newspaper immediately, even though nobody ordered one yet.&lt;br&gt;&lt;br&gt;
They would print out a considerable number of copies and pile them up by the storefront. When customers arrive, there's no need to wait for an operator to become available, place the phone call, pass the results to the scribbler, and wait for the final product. The newspaper is already there, waiting in a pile for the customers to read.&lt;br&gt;&lt;br&gt;
And this is how JAMStack websites work. They take the content, typically stored in flat files rather than databases or a clunkly webserver, apply it against layouts or templates, and generate a structure of purely static HTML files. These static HTML files are ready to be delivered to the users.&lt;br&gt;&lt;br&gt;
In terms of &lt;strong&gt;content management system (CMS)&lt;/strong&gt;, the difference between JAMStack and WordPress is that in JAMStack, CMS is used only for &lt;em&gt;"content management tasks"&lt;/em&gt;, not &lt;em&gt;templating and frontend content generation,&lt;/em&gt; making it easier for content managers and editors (those that don't have a technical background of the server-side of things, HTML files, or web development in general) to contribute to the content of the website or the web application.&lt;/p&gt;

&lt;p&gt;That's it for this week. In the next article of this series, I will give you an overview of how I set up my JAMStack blog before we dive into tutorials. Stay tuned!&lt;/p&gt;

</description>
      <category>jamstack</category>
    </item>
    <item>
      <title>Client-side JavaScript (JS) Frameworks - Part 1</title>
      <dc:creator>Thanh Truong</dc:creator>
      <pubDate>Wed, 10 Nov 2021 18:16:15 +0000</pubDate>
      <link>https://dev.to/thanhtr99270163/client-side-javascript-js-frameworks-part-1-fh3</link>
      <guid>https://dev.to/thanhtr99270163/client-side-javascript-js-frameworks-part-1-fh3</guid>
      <description>&lt;p&gt;JavaScript frameworks are an essential part of modern front-end web development, providing developers with tried and tested tools for building scalable, interactive web applications. Before we pick a framework and start learning about it, I think it's important that we first understand &lt;strong&gt;what a client-side JavaScript framework is, what it does and why it exists&lt;/strong&gt;. So, that's exactly what we will be learning in this article.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;In this article, we will:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Learn a brief history of JavaScript&lt;/li&gt;
&lt;li&gt;Dig deep to understand why JavaScript was created in the first place&lt;/li&gt;
&lt;li&gt;Explore main features of JavaScript frameworks&lt;/li&gt;
&lt;/ul&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  A brief history of JavaScript
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Why was JavaScript needed in the first place?&lt;/strong&gt; Good question!😉 Again, &lt;strong&gt;everything created was created to solve a problem.&lt;/strong&gt; So, what problems was JavaScript created to solve?&lt;/p&gt;

&lt;p&gt;Before JavaScript was created, web pages exist only as static documents. In the 90s, internet connectivity was very slow as we were still using dial-up connections with telephone lines and modems. Most user actions in the interface trigger an HTTP request back to a web server.&lt;/p&gt;

&lt;p&gt;Imagine a user filling out a form on a website. The validation of the input files on any form required a full round trip to the server. The server does some processing, retrieving data to validate the form values before returning an HTML page to the client. While the server is doing its thing, the user is waiting. And at every page reload, the user waits some more. This was not only a painful exercise as the internet speed was very slow but also resulted in the loss of data if the form was not filled out correctly. It lacks the inherent responsiveness of desktop applications.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Netscape Navigator&lt;/strong&gt; , one of the most popular web browsers in the 90s, sought out to solve this problem by finding a way to validate the input fields on the client-side without having to make a round trip to the server. This is how JavaScript was born, merely as a scripting language to validate forms on the client-side.&lt;/p&gt;

&lt;p&gt;To make it happen, Netscape turned to Brendan Eich, a software engineer with lots of experience with developing programming languages. At around the same time, Netscape laid the groundwork for a deal with &lt;strong&gt;Sun Microsystems&lt;/strong&gt;. The idea was to sign a deal with Sun Microsystems to license &lt;strong&gt;Java&lt;/strong&gt;. The preliminary concept was to embed &lt;strong&gt;Java Virtual Machine (JVM)&lt;/strong&gt; right in Navigator which would allow developers to build complex Java applications (later called &lt;strong&gt;applets&lt;/strong&gt; ) and run them on the web.&lt;/p&gt;

&lt;p&gt;However, given the nature of the web community, which was a cobbled-together community of hobbyists and enthusiasts. Some had years of experience in the computer science field. Others had none at all. Netscape realized that what they really needed was a "companion language" because Java is a very difficult language to manage without a background in computer science. It's extremely powerful, but relies on complex principles like &lt;strong&gt;object-oriented programming.&lt;/strong&gt; Therefore, any language made specifically for the web, needed to be both &lt;strong&gt;powerful&lt;/strong&gt; and &lt;strong&gt;approachable&lt;/strong&gt; to the average developer. Something that would allow developers to change text, move elements around, and generally experiment without errors flashing on screen every time they messed up something. A scripting language that could easily be embedded right into the HTML of a web page, that was still powerful enough to lay down a foundation for more adventurous programmers looking to build complex applications.&lt;/p&gt;

&lt;p&gt;That's what Eich was tasked with creating, and that was exactly what he delivered. JavaScript officially made it into the first beta version of Netscape Navigator 2.0, released in September of 1995. With just a simple &lt;code&gt;script&lt;/code&gt; tag, developers were able to create fairly complex applications.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--btxccAxf--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res-2.cloudinary.com/under-the-hood-learning/image/upload/q_auto/v1/blog_images/script-tag-html.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--btxccAxf--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res-2.cloudinary.com/under-the-hood-learning/image/upload/q_auto/v1/blog_images/script-tag-html.png" alt="Client-side JavaScript (JS) Frameworks - Part 1" width="880" height="487"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Why do we need JavaScript frameworks?
&lt;/h2&gt;

&lt;p&gt;When JavaScript debuted in 1996, it revolutionized how the web is used. It's no longer just a place to &lt;strong&gt;read things&lt;/strong&gt;, but to &lt;strong&gt;do things&lt;/strong&gt;. Originally, web pages were simple text pages that were used to share information in the form of text; there were no videos, games, animations, etc. A number of tools were later developed in order to allow the web to be as interactive as we know it today. &lt;strong&gt;Dynamic HTML (DHTML)&lt;/strong&gt; and &lt;strong&gt;Asynchronous JavaScript and XML (AJAX)&lt;/strong&gt; are two examples of such tools that are worth mentioning in the context of helping us understand the need for JavaScript frameworks.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;AJAX&lt;/strong&gt; and &lt;strong&gt;DHTML&lt;/strong&gt; are two technologies that are used in order to create more interactive web pages compared to the plain boring HTML pages. The main difference between DHTML and AJAX is that &lt;strong&gt;DHTML changes the elements on the web pages depending on user's actions&lt;/strong&gt; while &lt;strong&gt;AJAX allows the browser to request certain elements one at a time&lt;/strong&gt; in order to reduce the strain on the server and the Internet connection.&lt;/p&gt;

&lt;p&gt;Although it's possible to implement DHTML and AJAX with plain vanilla JavaScript, it's cumbersome. Therefore, developers who worked with JavaScript wrote tools to solve problems they faced and packaged them into reusable packages called &lt;strong&gt;libraries&lt;/strong&gt; , so they could share their solutions with others. This shared ecosystem of libraries eventually led to the development of several JavaScript frameworks. The development of these frameworks also redefined how the web is used. Modern, complex, interactive websites, referred to as &lt;strong&gt;web applications&lt;/strong&gt; now allow users to do things that used to be possible only in native applications installed on the user's computer.&lt;/p&gt;

&lt;p&gt;A &lt;strong&gt;framework&lt;/strong&gt; is &lt;strong&gt;a library that offers opinions about how software gets built.&lt;/strong&gt; These opinions allow for predictability and homogeneity in an application. &lt;strong&gt;Predictability&lt;/strong&gt; allows software to scale to an enormous size and still be maintainable.&lt;/p&gt;

&lt;h2&gt;
  
  
  Main features of JS frameworks
&lt;/h2&gt;

&lt;p&gt;Each major JS framework has a different approach to &lt;strong&gt;updating the DOM, handling browser events, and providing enjoyable developer experiences.&lt;/strong&gt; Below are some of the main features shared among different JS frameworks. Each framework may have its own implementation, but at the core, they all share these common features. A good understanding of these common features at a high level is very useful when it comes to deciding which framework to use for your application. So, let's dive in.🤿&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Domain-specific languages (DSLs)&lt;/strong&gt;
All JS frameworks use &lt;strong&gt;DSLs&lt;/strong&gt; in order to build applications. For example, &lt;strong&gt;React&lt;/strong&gt; uses &lt;strong&gt;JavaScript XML (JSX)&lt;/strong&gt;, &lt;strong&gt;Ember&lt;/strong&gt; uses &lt;strong&gt;Handlebars&lt;/strong&gt; , and &lt;strong&gt;Angular&lt;/strong&gt; uses &lt;strong&gt;TypeScript.&lt;/strong&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;blockquote&gt;
&lt;p&gt;A &lt;strong&gt;domain-specific language&lt;/strong&gt; is a computer language that's targeted to solve a particular kind of problem, rather than a general purpose language that's aimed at any kind of software problem.&lt;/p&gt;

&lt;p&gt;DSLs can't be read by the browser directly; they must be transformed into JavaScript or HTML first. Framework tooling generally includes the required tools to handle this transformation, or can be adjusted to include the necessary tools. While it is possible to build framework apps without using these DSLs, embracing them will streamline the development process.&lt;/p&gt;

&lt;p&gt;Examples of common DSLs are &lt;strong&gt;CSS, regular expressions, SQL, etc.&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Components&lt;/strong&gt;&lt;br&gt;&lt;br&gt;
Most frameworks have some kind of component model. Regardless of their opinions on how components should be written, each framework's components offer a way to describe the external &lt;strong&gt;properties&lt;/strong&gt; they may need, the internal &lt;strong&gt;state&lt;/strong&gt; that the component should manage, and the &lt;strong&gt;events&lt;/strong&gt; a user can trigger on the component's markup.&lt;br&gt;&lt;br&gt;
For example, &lt;strong&gt;React&lt;/strong&gt; components can be written with &lt;strong&gt;JSX&lt;/strong&gt; , &lt;strong&gt;Ember&lt;/strong&gt; components with &lt;strong&gt;Handlebars&lt;/strong&gt; , and &lt;strong&gt;Angular&lt;/strong&gt; and &lt;strong&gt;Vue&lt;/strong&gt; components with a templating syntax that lightly extends HTML.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Styling&lt;/strong&gt;&lt;br&gt;&lt;br&gt;
Each framework offers a way to define styles for components.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Dependency Handling&lt;/strong&gt;&lt;br&gt;&lt;br&gt;
As with other features, each framework provides its own mechanism for handling dependencies - using components inside other components. Components tend to import components into other components using the standard JS module syntax or something similar.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Rendering Elements&lt;/strong&gt;&lt;br&gt;&lt;br&gt;
Although each framework takes a slightly different approach in how components are rendered, all of them track the current rendered version of your browser's DOM, and make decisions about how the DOM should change as components in your application re-render.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Routing&lt;/strong&gt;&lt;br&gt;&lt;br&gt;
To avoid a broken experience in sufficiently complex apps with lots of views, each of the frameworks provides libraries that help developers implement client-side routing in their applications.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Testing&lt;/strong&gt;&lt;br&gt;&lt;br&gt;
Although testing tools are not built into the frameworks themselves, the command-line interface tools used to generate framework apps provide access to the appropriate testing tools for unit and integration testing.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;I hope you enjoyed a little bit of the history lesson in this article. I truly believe that the best way to learn is trying to understand the &lt;strong&gt;WHY&lt;/strong&gt; before the &lt;strong&gt;WHAT&lt;/strong&gt; and the &lt;strong&gt;HOW&lt;/strong&gt; , and one of the best ways to do that is to learn through history. In Part 2 of this article, we will explore the popular JavaScript frameworks throughout the history of web development. Stay tuned!&lt;/p&gt;

&lt;h2&gt;
  
  
  Photo Credits:
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;[Background photo created by wirestock - &lt;a href="http://www.freepik.com"&gt;www.freepik.com&lt;/a&gt; (&lt;a href="https://www.freepik.com/photos/background"&gt;https://www.freepik.com/photos/background&lt;/a&gt;)&lt;/li&gt;
&lt;/ol&gt;

</description>
      <category>javascriptclientside</category>
    </item>
  </channel>
</rss>
