<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/">
<channel>
<title><![CDATA[ButterCMS - Rafael Quintanilha]]></title>
<description><![CDATA[Essays about software engineering, web development, artificial intelligence, quantitative analysis, financial markets, books and tradition.]]></description>
<link>https://rafaelquintanilha.com/topic/buttercms/</link>
<image><url>https://rafaelquintanilha.com/content/images/2022/12/Logo-Design--2-.png</url><title>ButterCMS - Rafael Quintanilha</title><link>https://rafaelquintanilha.com/topic/buttercms/</link></image>
<lastBuildDate>Mon, 14 Oct 2024 19:48:28 GMT</lastBuildDate>
<atom:link href="https://rafaelquintanilha.com/topic/buttercms/rss/" rel="self" type="application/rss+xml"/>
<ttl>60</ttl>
<item>
<title><![CDATA[Leveraging Gatsby Incremental Builds With ButterCMS]]></title>
<description><![CDATA[Learn how to speed up your static builds with code examples.]]></description>
<link>https://rafaelquintanilha.com/leveraging-gatsby-incremental-builds-with-buttercms/</link>
<guid isPermaLink="false">63838a7b14168e003dd8f663</guid>
<category><![CDATA[Gatsby]]></category><category><![CDATA[ButterCMS]]></category><category><![CDATA[Netlify]]></category>
<dc:creator><![CDATA[Rafael Quintanilha]]></dc:creator>
<pubDate>Wed, 08 Dec 2021 18:08:00 GMT</pubDate>

<content:encoded><![CDATA[<p>In the first days of the web, all pages were <a href="https://buttercms.com/blog/what-is-a-static-site/" rel="noopener noreferrer" target="_blank"><em><strong>static</strong></em></a>. This meant that a typical communication between a client and a server happened just once when the user first loaded the page. At that time, all resources were fetched and the content was rendered to the screen. If later the user came back to the same page, as long as the content hadn’t changed, they would get the same result.</p>
<p>As time went on, the need for <em>dynamic</em> content became more apparent. For example, if I were at a <a href="https://buttercms.com/blog/using-zapier-zeit-and-buttercms-to-generate-a-news-aggregator-site/" rel="noopener noreferrer" target="_blank"><strong>news website</strong></a>, I would want to get fresh content. Or maybe if I were following stock market prices, I would want real-time data. Social network feeds could also be a clear use case for dynamic, always-changing content. As you can see, the static approach was doomed.</p>
<p>With <em>dynamic</em> architecture, though, data is pulled routinely. That way, your newsfeed can be regularly updated without the need for <em>requesting</em> new information. Plus, if only <em>part</em> of the content changes, all you need to do is fetch that part, preventing you from having to download all the data again. It’s a huge win.</p>
<figure class="image"><img alt="Static vs dynamic architecture" loading="lazy" decoding="async" width="1201" height="629" src="https://rafaelquintanilha.com/_astro/static-vs-dynamic-architecture--1-.DOMVrDt9_1A3nzu.webp"><figcaption>Static vs dynamic architecture</figcaption></figure>
<p>That model enabled the boom of <em>web applications</em>, given that web pages started to get more dynamic, more interactive, more powerful, and faster. Data is being constantly updated based on user actions, and because we are smart enough to pull only the freshest information, performance for complex applications has increased as well.</p>
<p>As good as it sounds, the dynamic model still has its flaws. First, because data is being constantly fetched, the application should be “mounted” on the fly, being loaded in chunks and either rendered asynchronously or after an unnecessarily long wait. Additionally, this wait is bad for SEO since the <em>web crawler</em> has to wait until the data is fetched and the page is mounted to be able to start properly indexing the application (and Google had limitations with that for years).</p>
<p>The static model overcomes these flaws. Because the content is already rendered and stored in the server, you download it only once (when you land on the page) and everything is ready to use. Crawlers are happy too — they can start indexing your page right away, saving your <a href="https://developers.google.com/search/blog/2017/01/what-crawl-budget-means-for-googlebot" rel="noopener noreferrer" target="_blank"><strong>crawl budget</strong></a>. Faster loading times plus no waste of crawl budget equals a higher-ranked SEO page, which in turn means more organic users, less money spent on advertising, more revenue, and so on. In short: static sites are less flexible but more SEO-friendly. The big question then becomes: is it possible to make them more malleable and still retain the SEO benefits?</p>
<h2 id="enter-server-side-rendered-apps"><strong>Enter server-side rendered apps</strong></h2>
<p>Server-Side Rendering (SSR) applications are, as the name suggests, rendered on the server. How is that different from the traditional <em>static</em> model?</p>
<p>In SSR architecture, the application is regularly built during the build phase. In each build, the freshest data available is gathered, which means that every build has dynamic content. This solves the problem for applications that aren’t time-sensitive. If your app can afford to update data, say, every 30 minutes, then an SSR approach might make sense for you. Every 30 minutes, you download the freshest data available, build (<em>render</em>) your page, and upload (<em>deploy</em>) the content to the server. Your users will then fetch the page as a static resource (like in the old days), and the content will be at most 30 minutes delayed.</p>
<figure class="image"><img alt="Server-Side Rendering" loading="lazy" decoding="async" width="1200" height="628" src="https://rafaelquintanilha.com/_astro/server-side-rendering--1-.BDl1K7Mh_ZcY38A.webp"><figcaption>Server-Side Rendering</figcaption></figure>
<p>Or maybe you have a website with content that doesn’t change very often, like a blog, but that you want to rebuild every time it changes (maybe a new edition is made or a new post is added.) In that scenario, you could set a <em>deploy hook</em> that would rebuild and deploy your application as needed.</p>
<p>Now, imagine this blog is really big. For example, it has thousands of entries. If you change page A, you really don’t want to rebuild all the other entries. That can get really problematic at scale. In other words, the desired effect is to rebuild only the content that changed, nothing else. Now how are we able to do that?</p>
<h2 id="incremental-builds"><strong>Incremental builds</strong></h2>
<p>The answer to this question lies in <em>incremental builds.</em> As the name suggests, and our intuition indicates, incremental builds will build only what is necessary (i.e. what has been added or updated.) A <em>full build</em>, on the other hand, rebuilds the whole application at once, notwithstanding the number of pages and the time needed to accomplish this.</p>
<figure class="image"><img alt="Standard vs Incremental Builds" loading="lazy" decoding="async" width="1201" height="629" src="https://rafaelquintanilha.com/_astro/standard-vs-incremental-build--1-.oQQMQ-dE_2rwTU1.webp"><figcaption>Standard vs Incremental Builds</figcaption></figure>
<p>In the big blog example, it means that when page A is modified or added, the others won’t be rebuilt. In terms of build time, this is a huge win—the faster your website is rebuilt, the sooner your users will have access to fresh data.</p>
<p>The benefits are not limited to only blog posts but product catalogs, social network profiles, stock market indicators, and basically everything that is bound to be read from a CMS can potentially make the most of incremental builds. In general, if your app relies on data from another source—for example, a CMS editor such as ButterCMS—incremental builds are a really smart choice.</p>
<h3 id="when-not-to-use-incremental-builds"><strong>When not to use Incremental Builds</strong></h3>
<p>Sometimes it'll be in your best interest to do a full build. For example, if you add a new feature to your application that is visible throughout the app (say, a sidebar), you will want it to be present on every page.</p>
<p>Also, as mentioned before, if your application is sensitive to real-time data then an SSR approach (and, therefore, incremental builds) won’t be adequate.</p>
<h2 id="gatsbys-approach-to-incremental-builds"><strong>Gatsby’s approach to incremental builds</strong></h2>
<p>When <a href="http://gatsbyjs.com/" rel="noopener noreferrer" target="_blank"><strong>Gatsby</strong></a> launched their <a href="https://www.gatsbyjs.com/products/cloud/" rel="noopener noreferrer" target="_blank"><strong>cloud service</strong></a>, one of the main benefits was — you guessed it — incremental builds, a long-awaited feature of the community.</p>
<p>As expected, this approach became very popular—to the point that since the launching of Gatsby v3 in March of 2021, <a href="https://www.gatsbyjs.com/blog/gatsby-v3/" rel="noopener noreferrer" target="_blank"><strong>incremental builds became available to everyone</strong></a> <em>by default.</em> Now, content creators who are integrating their CMS with Gatsby have this functionality right off the bat, allowing faster build times and better scalability.</p>
<p>Later, we will see how Gatsby’s incremental builds work in practice.</p>
<h2 id="leveraging-incremental-builds-with-buttercms"><strong>Leveraging incremental builds with ButterCMS</strong></h2>
<p>I mentioned before that incremental builds are particularly interesting for content creators. It gets even better for users who use a <a href="https://buttercms.com/blog/what-is-headless-cms/" rel="noopener noreferrer" target="_blank"><strong>headless CMS</strong></a>.</p>
<p>A headless CMS is a data source that abstracts away the need to change <em>code</em> when all you want to change is <em>content</em>. Suppose you want to deploy a landing page for a brand-new product of yours. Well, you may be working closely with the marketing team, tweaking texts, adding images, changing colors, and so on in a never-ending search for perfection. Now, if you have a team of engineers, it’s arguably not the best use of their time and expertise to tweak pixels on the screen.</p>
<p>A headless CMS is a solution for the aforementioned problem that delegates the creation of the landing page to a dedicated team and, later on, integrates the end result into your app.</p>
<p><a href="https://buttercms.com/" rel="noopener noreferrer" target="_blank"><strong>ButterCMS</strong></a> is an excellent example of a headless CMS. Butter users can create and edit landing pages in addition to maintaining posts and other content while integrating it easily with several programming languages. One of the most popular is Gatsby, which has a <a href="https://www.gatsbyjs.com/docs/sourcing-from-buttercms/" rel="noopener noreferrer" target="_blank"><strong>simple plugin</strong></a> to source data directly from ButterCMS in each build.</p>
<p>Now, if you have been following me since the beginning, you know what I’m getting at: Gatsby enables incremental builds when content changes by default (since v3), and also integrates seamlessly with ButterCMS. ButterCMS, in turn, is a headless CMS that empowers content creators. Can we connect them all and testify to the miracle of <em>incremental builds with Gatsby and ButterCMS?</em> Heck, yeah.</p>
<p>In the next section, we will learn how to create a simple Gatsby website that sources data from ButterCMS. We will also deploy this application to <a href="https://www.netlify.com/" rel="noopener noreferrer" target="_blank"><strong>Netlify</strong></a> to understand how incremental builds work in practice.</p>
<h2 id="tutorial-creating-a-simple-blog-using-buttercms-and-gatsbys-incremental-builds"><strong>Tutorial: Creating a simple blog using ButterCMS and Gatsby’s incremental builds</strong></h2>
<h3 id="before-you-begin"><strong>Before you begin</strong></h3>
<p>There are a couple of things you are going to need in order to follow through with this tutorial. One of them is a ButterCMS account. Go to <a href="https://buttercms.com/join" rel="noopener noreferrer" target="_blank"><strong>https://buttercms.com/join</strong></a> and sign up, if you still haven’t. Once you are logged in, click on your account and hit “Settings.” Select the “API Keys” tab and copy what is under “Read API Token,” which we will need to fetch information from Butter. Make sure to store it safely.</p>
<p>Next, make sure you have NodeJS installed. <a href="https://www.gatsbyjs.com/docs/tutorial/part-0/#nodejs" rel="noopener noreferrer" target="_blank"><strong>Gatsby’s Docs have a section</strong></a> explaining how to do it for every OS. Also, it’s a good idea to follow through with their tutorial if you are a complete newbie to Gatsby.</p>
<p>Finally, create an account on Netlify. We will host our application there (don’t worry, it’s free!) so we can see in practice how incremental builds work in a production environment. We’ll get to that part later.</p>
<h3 id="what-were-building"><strong>What we're building</strong></h3>
<p>To showcase how incremental builds work, we are going to build an application that pulls posts from ButterCMS. We will render this content to our site and watch how builds react as content changes.</p>
<h3 id="step-1-creating-a-gatsby-app"><strong>Step 1: Creating a Gatsby app</strong></h3>
<p>The first thing to do is to create the Gatsby application. Follow their <a href="https://www.gatsbyjs.com/docs/quick-start/" rel="noopener noreferrer" target="_blank"><strong>quick start</strong></a> to create an initial boilerplate. Don’t worry about all the customizations; we are not going to need them now. After completing the quick start, make sure you can visit localhost:8000 and see your brand-new Gatsby app.</p>
<h3 id="step-2-sourcing-data-from-buttercms"><strong>Step 2: Sourcing data from ButterCMS</strong></h3>
<p>Our app is so far pretty simple. We are going to color it a bit by integrating data with ButterCMS. The first thing you want to do, if you haven’t already, is to add some content in Butter!</p>
<p>In Butter’s admin panel, click on “Blog posts” in the side menu and add a couple of entries. In the end, it should look something like this:</p>
<figure class="image"><img alt="ButterCMS admin panel" loading="lazy" decoding="async" width="1023" height="786" src="https://rafaelquintanilha.com/_astro/incremental-builds-buttercms-blog-posts--1-.DtWZITcX_ZP9Ixs.webp"><figcaption>ButterCMS admin panel</figcaption></figure>
<p>Now that we have actual content in our CMS, we are ready to <em>source it</em> in Gatsby. As mentioned before, Gatsby and Butter have a handy integration plugin called <em>gatsby-source-buttercms.</em> You can follow the <a href="https://www.gatsbyjs.com/docs/sourcing-from-buttercms/" rel="noopener noreferrer" target="_blank"><strong>official docs from Gatsby</strong></a> for more context.</p>
<p>In your project’s directory, add the plugin:</p>
<p><code>$ npm install gatsby-source-buttercms</code></p>
<p>Once the installation is done, open <em>gatsby-config.js</em> and add the following to the <em>plugins</em> array:</p>
<figure class="code"><figcaption>javascript</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="javascript"><code><span class="line"><span style="color:#A1C1E4">...</span></span>
<span class="line"><span style="color:#ECEBE8">{</span></span>
<span class="line"><span style="color:#ECEBE8">      resolve: </span><span style="color:#97CCAE">`gatsby-source-buttercms`</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#ECEBE8">      options: {</span></span>
<span class="line"><span style="color:#ECEBE8">        authToken: YOUR_TOKEN</span></span>
<span class="line"><span style="color:#ECEBE8">      },</span></span>
<span class="line"><span style="color:#ECEBE8">    },</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span></code></pre></figure>
<p>Replacing <em>YOUR_TOKEN</em> with the token you grabbed from Butter’s panel before. If everything is correct, start the Gatsby server again and go to <a href="http://localhost:8000/___graphql" rel="noopener noreferrer" target="_blank"><strong>http://localhost:8000/___graphql</strong></a> where you should be able to see this:</p>
<figure class="image"><img alt="GraphQL interface" loading="lazy" decoding="async" width="1111" height="559" src="https://rafaelquintanilha.com/_astro/incremental-builds-local-host-1--1-.sDD9xK55_Z2l4x9w.webp"><figcaption>GraphQL interface</figcaption></figure>
<p>Note how there are Butter <a href="https://www.gatsbyjs.com/docs/reference/graphql-data-layer/node-interface/" rel="noopener noreferrer" target="_blank"><strong>nodes</strong></a> in the Explorer! You can easily test that the data is available by writing the following query to the interface:</p>
<figure class="code"><figcaption>javascript</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="javascript"><code><span class="line"><span style="color:#ECEBE8">query MyQuery {</span></span>
<span class="line"><span style="color:#ECEBE8">  allButterPost {</span></span>
<span class="line"><span style="color:#ECEBE8">    nodes {</span></span>
<span class="line"><span style="color:#ECEBE8">      title</span></span>
<span class="line"><span style="color:#ECEBE8">      author {</span></span>
<span class="line"><span style="color:#ECEBE8">        first_name</span></span>
<span class="line"><span style="color:#ECEBE8">        last_name</span></span>
<span class="line"><span style="color:#ECEBE8">      }</span></span>
<span class="line"><span style="color:#ECEBE8">    }</span></span>
<span class="line"><span style="color:#ECEBE8">  }</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span></code></pre></figure>
<p>Now you should see the title of your posts and the author’s name in the right-side panel. Nice job! Gatsby and ButterCMS are now hooked up!</p>
<h3 id="step-3-rendering-data-in-gatsby"><strong>Step 3: Rendering data in Gatsby</strong></h3>
<p>Now, our app is sourcing data from Butter, but we are still not seeing it. Thankfully, this is the easy part!</p>
<p>For our proof-of-concept, we are going to create three pages:</p>
<ol>
<li>A home page, which will have no information from Butter;</li>
<li>A blog index, which will render the title of all posts and link to them;</li>
<li>A post template, which will be used to dynamically render every post added in Butter.</li>
</ol>
<p>Our goal, when debugging incremental builds, will be to assert the following:</p>
<ul>
<li>A code change triggers a rebuild for all pages;</li>
<li>A content change triggers a rebuild only for the pages that contain that content (the blog index and the corresponding post):</li>
<li>As a corollary, if I change post A, then the home page and post B shouldn’t be rebuilt.</li>
</ul>
<p>Create the blog index component:</p>
<figure class="code"><figcaption>javascript</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="javascript"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> React </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> "react"</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> Layout </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> "../components/layout"</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> { useStaticQuery, graphql, Link } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> "gatsby"</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> { content } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> "./blog.module.css"</span><span style="color:#ECEBE8">;</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> Blog</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#ECEBE8">    allButterPost: { nodes: posts },</span></span>
<span class="line"><span style="color:#ECEBE8">  } </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> useStaticQuery</span><span style="color:#ECEBE8">(</span><span style="color:#EDCC95">graphql</span><span style="color:#97CCAE">`</span></span>
<span class="line"><span style="color:#97CCAE">    query MyQuery {</span></span>
<span class="line"><span style="color:#97CCAE">      allButterPost {</span></span>
<span class="line"><span style="color:#97CCAE">        nodes {</span></span>
<span class="line"><span style="color:#97CCAE">          title</span></span>
<span class="line"><span style="color:#97CCAE">          slug</span></span>
<span class="line"><span style="color:#97CCAE">        }</span></span>
<span class="line"><span style="color:#97CCAE">      }</span></span>
<span class="line"><span style="color:#97CCAE">    }</span></span>
<span class="line"><span style="color:#97CCAE">  `</span><span style="color:#ECEBE8">);</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">  return</span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;</span><span style="color:#A1C1E4">Layout</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;</span><span style="color:#A1C1E4">h1</span><span style="color:#ECEBE8">>My Blog&#x3C;/</span><span style="color:#A1C1E4">h1</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;</span><span style="color:#A1C1E4">ul</span><span style="color:#EDCC95"> className</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{content}></span></span>
<span class="line"><span style="color:#ECEBE8">          {</span><span style="color:#EDCC95">posts.map</span><span style="color:#ECEBE8">((post) </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">            &#x3C;</span><span style="color:#A1C1E4">li</span><span style="color:#EDCC95"> key</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{post.slug}></span></span>
<span class="line"><span style="color:#ECEBE8">              &#x3C;</span><span style="color:#A1C1E4">Link</span><span style="color:#EDCC95"> to</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{</span><span style="color:#97CCAE">`/blog/${</span><span style="color:#97CCAE">post.slug</span><span style="color:#97CCAE">}`</span><span style="color:#ECEBE8">}>{post.title}&#x3C;/</span><span style="color:#A1C1E4">Link</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">            &#x3C;/</span><span style="color:#A1C1E4">li</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">          ))}</span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;/</span><span style="color:#A1C1E4">ul</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;/</span><span style="color:#A1C1E4">Layout</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">  );</span></span>
<span class="line"><span style="color:#ECEBE8">};</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">export</span><span style="color:#A1C1E4"> default</span><span style="color:#ECEBE8"> Blog;</span></span></code></pre></figure>
<p>And the post template:</p>
<figure class="code"><figcaption>javascript</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="javascript"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> React </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> "react"</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> { Link, graphql } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> "gatsby"</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> Layout </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> "./layout"</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> { container, back, body } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> "./post.module.css"</span><span style="color:#ECEBE8">;</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> PostTemplate</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> ({ data }) </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  return</span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;</span><span style="color:#A1C1E4">Layout</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#EDCC95"> className</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{container}></span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;</span><span style="color:#A1C1E4">Link</span><span style="color:#EDCC95"> className</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{back} </span><span style="color:#EDCC95">to</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"/blog"</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">          ⇦ Go back</span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;/</span><span style="color:#A1C1E4">Link</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;</span><span style="color:#A1C1E4">h1</span><span style="color:#ECEBE8">>{data.butterPost.title}&#x3C;/</span><span style="color:#A1C1E4">h1</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;</span><span style="color:#A1C1E4">div</span></span>
<span class="line"><span style="color:#EDCC95">          className</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{body}</span></span>
<span class="line"><span style="color:#EDCC95">          dangerouslySetInnerHTML</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{{ __html: data.butterPost.body }}</span></span>
<span class="line"><span style="color:#ECEBE8">        /></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;/</span><span style="color:#A1C1E4">Layout</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">  );</span></span>
<span class="line"><span style="color:#ECEBE8">};</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">export</span><span style="color:#A1C1E4"> const</span><span style="color:#ECEBE8"> query </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> graphql</span><span style="color:#97CCAE">`</span></span>
<span class="line"><span style="color:#97CCAE">  query ($slug: String!) {</span></span>
<span class="line"><span style="color:#97CCAE">    butterPost(slug: { eq: $slug }) {</span></span>
<span class="line"><span style="color:#97CCAE">      title</span></span>
<span class="line"><span style="color:#97CCAE">      body</span></span>
<span class="line"><span style="color:#97CCAE">    }</span></span>
<span class="line"><span style="color:#97CCAE">  }</span></span>
<span class="line"><span style="color:#97CCAE">`</span><span style="color:#ECEBE8">;</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">export</span><span style="color:#A1C1E4"> default</span><span style="color:#ECEBE8"> PostTemplate;</span></span></code></pre></figure>
<p>For the sake of simplicity, I’m not going into Gatsby’s details in this tutorial, but you have access to the full code at <a href="https://github.com/ButterCMS/gatsby-incremental-builds" rel="noopener noreferrer" target="_blank"><strong>https://github.com/ButterCMS/gatsby-incremental-builds</strong></a>. A live example can be found at <a href="https://incremental-builds.netlify.app/" rel="noopener noreferrer" target="_blank"><strong>https://incremental-builds.netlify.app/</strong></a>.</p>
<p>If you follow through the repository (or clone it and switch the <em>authToken</em> with your own), you will see something like this:</p>
<figure class="image"><img alt="Blog page" loading="lazy" decoding="async" width="1033" height="803" src="https://rafaelquintanilha.com/_astro/incremental-builds-blog-page.DVz5j5Vq_ZtGCBb.webp"><figcaption>Blog page</figcaption></figure>
<p>See how the content of the post you added in ButterCMS is correctly rendered in your app? Congratulations, you have successfully combined Butter and Gatsby!</p>
<h3 id="step-4-deploying-to-netlify"><strong>Step 4: Deploying to Netlify</strong></h3>
<p>Now that our app is complete, it’s time to make it available to the world. <a href="https://app.netlify.com/" rel="noopener noreferrer" target="_blank"><strong>Log in to Netlify</strong></a> and click on “New site from git.”</p>
<p><em>Note: It’s a good time to create a repository for your own app. I recommend</em> <a href="https://github.com/" rel="noopener noreferrer" target="_blank"><em><strong>GitHub</strong></em></a><em>. Follow the instructions on their website to store your code in the cloud and get Git benefits.</em></p>
<p><em>Warning:</em> <em><strong>do</strong></em> <em><strong>not</strong></em> <em>commit your ButterCMS token to any Git provider. When using Netlify,</em> <a href="https://docs.netlify.com/configure-builds/environment-variables/" rel="noopener noreferrer" target="_blank"><em><strong>Netlify environment variables</strong></em></a> <em>are preferred instead.</em></p>
<p>When creating your new site, make sure to replace the <em>Build</em> command with:</p>
<p><code>gatsby build --verbose --log-pages</code></p>
<p>This will be necessary to gather more information about built pages. <a href="https://www.gatsbyjs.com/docs/debugging-incremental-builds/" rel="noopener noreferrer" target="_blank"><strong>Gatsby Docs</strong></a> have a dedicated page on how to debug incremental builds.</p>
<p>If all is good, you should be able to start a deploy for your app and see something like this in the logs:</p>
<figure class="image"><img alt="Deploy summary" loading="lazy" decoding="async" width="340" height="321" src="https://rafaelquintanilha.com/_astro/deploy-summary-1-1.B8fEYM7v_Z1re1co.webp"><figcaption>Deploy summary</figcaption></figure>
<figure class="image"><img alt="Deploy logs" loading="lazy" decoding="async" width="453" height="216" src="https://rafaelquintanilha.com/_astro/deploy-summary-2-1.BpxBaFOt_252NzP.webp"><figcaption>Deploy logs</figcaption></figure>
<p>Note how Netlify discerns all pages and assets built during that phase. If you scroll down the logs, you will be able to see more detailed information on the number of pages updated and how long it took for Gatsby to build them.</p>
<h3 id="step-5-hooking-netlify-deploys-to-content-changes"><strong>Step 5: Hooking Netlify deploys to content changes</strong></h3>
<p>The penultimate step remaining in your build puzzle is to “hook” every change in Butter’s content to a new deploy in Netlify. This way, every time a post is either published or updated in the Butter interface, we trigger a new build in Netlify. This build will generate new static assets (only if the content has changed) and then deploy them to the server. New visitors will be served with the updated content as soon as the deploy is complete.</p>
<p>In Netlify, go to “Site settings” and then “Build &#x26; deploy.” Scroll down to “Build hooks” and click on “Add build hook”. Give it a descriptive name and, in the end, you should see something like this:</p>
<figure class="image"><img alt="Netlify Build hooks" loading="lazy" decoding="async" width="922" height="327" src="https://rafaelquintanilha.com/_astro/netlify-build-hooks.BWDwJ5Tp_2jHQc7.webp"><figcaption>Netlify Build hooks</figcaption></figure>
<p>Copy the URL (the “hook”) and head to Butter’s panel. Go back to “Settings” again and, in the “Webhooks” tab, add the copied URL as the Target URL. Leave “Header” blank and select <em>post.published - blog post is published</em> in the Event field. Hit “Save” and we are done! Now, every time any post is published, a new build will be triggered.</p>
<p>In order to test that, go to your Blog posts and change something in one of the posts. Note that Netlify will automatically start a new build and that by the end of it only the affected pages (the post itself and the index with all posts) will be rebuilt!</p>
<figure class="image"><img alt="Deploy summary after changes" loading="lazy" decoding="async" width="372" height="221" src="https://rafaelquintanilha.com/_astro/deploy-summary-after-change-1.Cpit-Gif_2uS6dL.webp"><figcaption>Deploy summary after changes</figcaption></figure>
<figure class="image"><img alt="Deploy logs after changes" loading="lazy" decoding="async" width="442" height="128" src="https://rafaelquintanilha.com/_astro/deploy-summary-after-change-2.C-mKF-Kb_ccWDd.webp"><figcaption>Deploy logs after changes</figcaption></figure>
<p>Note how this build was faster (10s now vs 15s before). Now, imagine the difference if you had hundreds or thousands of pages of static content!</p>
<p><em>Note: Due to cache reasons it might be that the incremental builds kick in only after you have rebuilt your site at least once.</em></p>
<p>As a final test, change something in your Gatsby code and push it to your Git provider. As expected, <em>all</em> pages will be rebuilt, as mentioned in <a href="https://www.gatsbyjs.com/docs/debugging-incremental-builds/#expected-behaviors" rel="noopener noreferrer" target="_blank"><strong>Gatsby’s Docs as expected behavior</strong></a>. In short: incremental builds will be applied whenever <em>content</em> changes, but full builds are expected when your <em>code</em> changes.</p>
<h3 id="step-6-previewing-draft-content-before-publishing"><strong>Step 6: Previewing draft content before publishing</strong></h3>
<p>There is one last enhancement that can be done in order to streamline our process even more. In the previous step, we set up a webhook that rebuilds the website when a new post is <em>published</em> or <em>updated</em>. That’s really great, but in a working environment, the experience would be subpar. Oftentimes, content creators will want to double-check and preview their work before publishing it to a production environment.</p>
<p>Luckily, there’s a way to circumvent this limitation with ButterCMS! All we need to do is to set up a proper <em>staging</em> environment. I will walk you through how to do it in Netlify in a moment, but before that, create a <em>staging</em> branch in your repo:</p>
<p><code>$ git checkout -b staging</code></p>
<p>Now that you are in a different branch, the only code change needed is to tell <em>gatsby-source-buttercms</em> that you also want to source data in a <em>draft</em> state. Go to <em>gatsby-config.js</em> again and add the following line:</p>
<figure class="code"><figcaption>javascript</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="javascript"><code><span class="line"><span style="color:#A1C1E4">...</span></span>
<span class="line"><span style="color:#ECEBE8">{</span></span>
<span class="line"><span style="color:#ECEBE8">      resolve: </span><span style="color:#97CCAE">`gatsby-source-buttercms`</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#ECEBE8">      options: {</span></span>
<span class="line"><span style="color:#ECEBE8">        authToken: YOUR_TOKEN,</span></span>
<span class="line"><span style="color:#ECEBE8">        preview: </span><span style="color:#97CCAE">1</span></span>
<span class="line"><span style="color:#ECEBE8">      },</span></span>
<span class="line"><span style="color:#ECEBE8">    },</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span></code></pre></figure>
<p>Surprisingly, that’s all you need code-wise! As a side note, you could try to use environment variables to spawn multiple environments based on the same code.</p>
<p>Let us now set up the <em>staging</em> environment. Hop back to Netlify and create a new site. Again, we are taking the simpler step here. If you have a custom domain registered with Netlify, you can leverage <a href="https://docs.netlify.com/domains-https/custom-domains/multiple-domains/#branch-subdomains" rel="noopener noreferrer" target="_blank"><strong>branch subdomains</strong></a> instead of setting up a new site.</p>
<p>Repeat the procedure done in Step 4, only this time selecting <em>staging</em> as the “Branch to deploy.” Your configuration should look similar to this:</p>
<figure class="image"><img alt="Branch subdomains configuration" loading="lazy" decoding="async" width="725" height="880" src="https://rafaelquintanilha.com/_astro/branch-to-deploy-configuration.B8Oj8217_ApLsF.webp"><figcaption>Branch subdomains configuration</figcaption></figure>
<p>Proceed to deploy and don’t forget to add your ButterCMS API key as an environment variable to the site recently created.</p>
<p>Next, repeat Step 5 and create a new webhook both in Netlify and ButterCMS. Make sure to add the URL generated by Netlify as the <em>Target URL</em> in Butter’s Webhooks tab and, this time, select <em>post.draft - draft post is saved</em> in the Event field. Your Butter’s webhooks should look like this:</p>
<figure class="image"><img alt="ButterCMS webhooks" loading="lazy" decoding="async" width="1345" height="543" src="https://rafaelquintanilha.com/_astro/buttercms-webhooks.CPDm10S7_2hwbKy.webp"><figcaption>ButterCMS webhooks</figcaption></figure>
<p>As is, our app already has a working preview environment: every time a new draft post is <em>created</em> or <em>saved</em>, a webhook will be triggered to rebuild our <em>staging</em> site in Netlify. This way, content creators can iterate and observe how it looks on the real page before actually publishing to the production site.</p>
<p>The only caveat is that previewing happens <em>outside</em> Butter — well, not anymore! The last step in this tutorial is to set up <em>Previews</em> in Butter’s settings, which means that ButterCMS will become the one-stop shop for your content creators.</p>
<p>Click on the “Previews” tab and add the template URL to the <em>Blog Posts</em> field. In our case, it will look like: https://your-staging-site-url.netlify.app/blog/&#x3C;slug>. The green part is what we defined in <em>gatsby-node.js</em>, only now using <em>&#x3C;slug></em> as the slug placeholder.</p>
<p>And that’s it! All technical details are done. Try your setup by creating a new post, but instead of clicking on “Publish,” select “Save draft.” Check that only your staging site was rebuilt, while the production site remained unchanged. Compare how the blog index is different in the <a href="https://staging-incremental-builds.netlify.app/blog" rel="noopener noreferrer" target="_blank"><strong>staging</strong></a> and live <a href="https://incremental-builds.netlify.app/blog" rel="noopener noreferrer" target="_blank"><strong>production</strong></a> environments.</p>
<p>Note that you can keep editing your content in Butter and, whenever “Save draft” is clicked, a new rebuild will be triggered. Click on the “Preview” button while editing to see your changes right inside Butter’s panel! Hopefully, once we are leveraging incremental builds, the rebuild will be really fast and the new content will be readily available.</p>
<figure class="image"><img alt="Previewing changes" loading="lazy" decoding="async" width="1744" height="1250" src="https://rafaelquintanilha.com/_astro/buttercms-preview-example--1-.iBsxC4M-_Zezb9s.webp"><figcaption>Previewing changes</figcaption></figure>
<h2 id="conclusion"><strong>Conclusion</strong></h2>
<p>Today, we learned the motivation behind incremental builds and the problems they are trying to solve. We gathered all information in a tutorial hooking up ButterCMS and Gatsby, which has incremental builds enabled for free by default since v3.</p>
<p>Incremental builds are and will no doubt continue to be beneficial for content creators, especially the ones leveraging a Gatsby-compatible <a href="https://buttercms.com/blog/what-is-headless-cms/" rel="noopener noreferrer" target="_blank"><strong>headless CMS</strong></a> such as ButterCMS. By significantly decreasing build times, your website will be able to scale properly as new content is added for the enjoyment of your audience.</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[How to Rebuild Static Sites at Fixed Intervals with Netlify and GitHub Actions]]></title>
<description><![CDATA[Learn how to schedule redeployments at regular intervals by building a simple application that fetches stock market data.]]></description>
<link>https://rafaelquintanilha.com/how-to-rebuild-static-sites-at-fixed-intervals-with-netlify-and-github-actions/</link>
<guid isPermaLink="false">6383a8f614168e003dd8f6e6</guid>
<category><![CDATA[Gatsby]]></category><category><![CDATA[Netlify]]></category><category><![CDATA[ButterCMS]]></category>
<dc:creator><![CDATA[Rafael Quintanilha]]></dc:creator>
<pubDate>Tue, 15 Jun 2021 18:23:00 GMT</pubDate>

<content:encoded><![CDATA[<figure class="image"><img alt="Setting up cron jobs with GitHub Actions and Netlify" loading="lazy" decoding="async" width="600" height="600" src="https://rafaelquintanilha.com/_astro/illustration-edit-cron-jobs.CwrUK8wq_2bJdlY.webp"><figcaption>Setting up cron jobs with GitHub Actions and Netlify</figcaption></figure>
<p>Back in the old days, websites were all static. That meant that all content rendered on the page was fetched previously from the server and no change would take place until the files were updated. Time has passed and the need for <em>dynamic</em> data has increased — now users are demanding faster, timelier updates and the traditional model has become outdated.</p>
<p>Technologies like React, which can be used with our <a href="https://buttercms.com/react-cms/" rel="noopener noreferrer" target="_blank"><strong>React CMS</strong></a>, popularized the concept of client-side apps, where the browser would download the JavaScript from the server and render the whole app from there. If further data was needed, the application would issue as many HTTP requests as needed in order to get recent, up-to-date information.</p>
<p>The idea was great and people quickly adopted it. However, this approach had some shortcomings: because the application had to be constructed from scratch <em>after</em> the JavaScript was downloaded <em>and</em> parsed, larger apps could face performance issues. Moreover, SEO was a problem since web crawlers had less time to get available content to index your web page (only after <a href="https://searchengineland.com/tested-googlebot-crawls-javascript-heres-learned-220157" rel="noopener noreferrer" target="_blank"><strong>they got smart enough to crawl JavaScript</strong></a>).</p>
<p>In order to address these issues and retain the good from the dynamic approach, the concept of <em>server-side rendered</em> applications was introduced. Now, the app is rendered on the server during a phase called <em>build time</em>, which yields a bunch of static files to be served very much like the old days. During build time, data can be sourced from different places (e.g. a database, an external API, etc), which enables the static file to actually have dynamic information.</p>
<p>Now, considering that all data is fetched during build time, the app is as up-to-date as the last build. This means that if you don’t routinely <em>rebuild</em> it, your app won’t differ very much from the traditional model.</p>
<p>The goal of this article is to explain how you can easily set up and edit cron jobs to schedule a build for your static website at regular intervals, so you can use the latest cutting-edge tools for web development and still retain the ability to create SEO-friendly applications.</p>
<h2 id="what-is-a-cron-job"><strong>What is a cron job?</strong></h2>
<p>A <em>cron job</em> is simply a task scheduled to be executed at defined intervals. You can instruct a computer program to perform a routine at those intervals using a <em>crontab</em>.</p>
<p>Crontabs follow a specific structure that can be quickly learned. Fortunately, there are applications such as <a href="https://crontab.guru/" rel="noopener noreferrer" target="_blank"><strong>crontab guru</strong></a> that help you to edit cron jobs very easily. Diving into the specifics of crontabs is out of the scope of this article, but as a quick example, the following is the cron structure necessary to run a task at 8 pm every weekday:</p>
<figure class="code"><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="text"><code><span class="line"><span>0  20  *  *  1-5</span></span></code></pre></figure>
<p>The first position (0) is the <em>minute</em> that the task must be executed. The next one (20), is the hour. Combining both, we are instructing the computer to execute the task at minute 0 of the 20th hour (8 pm).</p>
<figure class="image"><img alt="Editing cron jobs illustration" loading="lazy" decoding="async" width="600" height="600" src="https://rafaelquintanilha.com/_astro/edit-cron-jobs.D60I0R_A_1udlbm.webp"><figcaption>Editing cron jobs illustration</figcaption></figure>
<p>The third position states the <em>day of the month,</em> while the fourth position is about the <em>month</em> itself. An asterisk means that <em>any</em> value is fine for both entries. Finally, the last value is the day of the week, where we are instructing the computer to only execute on days 1 to 5 (starting from 0, which is Sunday). Therefore, only days from Monday to Friday are included. We can view a nice, human-readable description of cron <a href="https://crontab.guru/#0_18_*_*_1-5" rel="noopener noreferrer" target="_blank"><strong>here</strong></a>.</p>
<h2 id="netlify-build"><strong>Netlify Build</strong></h2>
<p>Earlier we learned that <em>server-side rendered</em> applications render static files during their <em>build</em>. In a production environment, it is important that you are able to automatically <em>trigger</em> a build so you can set up a workflow for the deployment of your website.</p>
<p>One of the many tools available nowadays is <a href="https://www.netlify.com/products/build/" rel="noopener noreferrer" target="_blank"><strong>Netlify Build</strong></a>. Netlify Build is a modern way to go from code to deployment without too much of a hassle. As the name suggests, it takes care of building your website and deploying the output to the internet. There are several articles explaining how to use Netlify and its benefits (including <a href="https://buttercms.com/blog/what-is-serverless-and-how-to-use-it-in-practice/" rel="noopener noreferrer" target="_blank"><strong>What is Serverless and How to Use It in Practice</strong></a>) but if you haven’t used it yet, don’t worry — we are going to see how it works step by step.</p>
<figure class="image"><img alt="Netlify and GitHub communicating" loading="lazy" decoding="async" width="600" height="600" src="https://rafaelquintanilha.com/_astro/website-build.DYJAfqvI_Z2jKeYq.webp"><figcaption>Netlify and GitHub communicating</figcaption></figure>
<h3 id="build-hooks">Build hooks</h3>
<p>Considering that Netlify allows you to trigger builds, a natural question is how can you programmatically instruct Netlify that a build is due.</p>
<p>Fortunately, Netlify provides what are called <a href="https://docs.netlify.com/configure-builds/build-hooks/" rel="noopener noreferrer" target="_blank"><em><strong>build hooks</strong></em></a>. In their own words, <em>build hooks are URLs you can use to trigger new builds and deploys</em>. It means that every time you make a POST request to the provided URL, you are able to trigger a build.</p>
<p>We are getting closer to our goal: we know already that we can rebuild and deploy static websites using Netlify and that there is a unique URL that can be used to trigger a build programmatically. If we find a way to make POST requests at regular intervals, then we will be able to schedule builds for our static website.</p>
<h2 id="github-actions"><strong>GitHub Actions</strong></h2>
<p>The answer to this problem lies in a feature called <a href="https://github.com/features/actions" rel="noopener noreferrer" target="_blank"><strong>GitHub Actions</strong></a>. Actions are a very powerful service offered by GitHub that can leverage your application’s CI/CD (continuous integration and deployment) workflow. We are not getting into details of all the advantages that Actions can provide to you, but I suggest reading <a href="https://docs.github.com/en/actions" rel="noopener noreferrer" target="_blank"><strong>their docs</strong></a> in order to get a broader understanding of it.</p>
<p>For today, what is important is that GitHub Actions allow us to issue a cURL request at regular intervals. This fills the last piece of our puzzle. Here’s how our workflow looks:</p>
<ol>
<li>Host server-side rendered application on Netlify and generate unique build hook URL;</li>
<li>Set up a GitHub action to make a POST request to that URL at regular intervals;</li>
<li>Enjoy a fast, SEO-friendly application using cutting-edge technologies with data updated as scheduled.</li>
</ol>
<p>We are going to fit all the pieces together in a practical project, but before we get into it, let us discuss the implications and shortcomings of such an approach.</p>
<h2 id="limitations-of-scheduled-cron-jobs"><strong>Limitations of scheduled cron jobs</strong></h2>
<p>All looks very well but as with everything in life, there are some constraints.</p>
<p>Most importantly, even if we schedule builds at reduced intervals, our data will never be <em>real-time.</em> As always, it is part of the engineering job to decide the best tool for the task at hand, and if your application is very sensitive to real-time information, going server-side rendered might not be the best choice for you.</p>
<p>Moreover, if you significantly reduce the interval, you will perform more builds, which means that you are going to spend more <em>build minutes</em>. Many build tools charge by the minute, and even though most services will provide you a free tier, triggering too many builds can stack up minutes quickly and cost you a lot of money.</p>
<figure class="image"><img alt="Waiting for your code to execute" loading="lazy" decoding="async" width="600" height="600" src="https://rafaelquintanilha.com/_astro/performance-issues.B0xtYAea_Z1ecA4J.webp"><figcaption>Waiting for your code to execute</figcaption></figure>
<p>Also note that if your build is heavy, meaning that it fetches too much information or builds too many pages, every build will also take more time to complete. This will directly impact costs.</p>
<p>That said, setting up cron jobs to trigger static builds is a fairly elegant solution if your application can afford small delays (like updating once a day or every X hours). Remember that the ultimate goals for a static website are to be <em>fast</em> and <em>SEO-friendly</em>, and if you have dynamic, real-time pages, such as a social network feed, you probably won’t want it to be statically rendered anyway.</p>
<p>Enough talk. Let's learn how to implement all the concepts explained so far in a practical project.</p>
<h2 id="how-to-schedule-and-edit-cron-jobs"><strong>How to schedule and edit cron jobs</strong></h2>
<p>To illustrate the process, we will create a basic static stock price website. Our project will be very simple: we are going to build an application where users will be able to check how much the stock prices of FAANG companies have changed since the last trading day.</p>
<p>The application will be statically generated using <a href="https://www.gatsbyjs.com/" rel="noopener noreferrer" target="_blank"><strong>GatsbyJS</strong></a> and will fetch data from <a href="https://finance.yahoo.com/" rel="noopener noreferrer" target="_blank"><strong>Yahoo Finance’s API</strong></a>. On top of that, we will set up a GitHub Action to trigger a build every workday at the end of the regular trading session (4 pm ET or 8 pm UTC). You can check the source code at any point on the <a href="https://github.com/rafaelquintanilha/faang-variation" rel="noopener noreferrer" target="_blank"><strong>GitHub repo</strong></a>. The final version will look like <a href="http://faangvariation.netlify.app/" rel="noopener noreferrer" target="_blank"><strong>this</strong></a>.</p>
<h3 id="step-1-cloning-the-gatsby-repository">Step 1: Cloning the Gatsby repository</h3>
<p>In order to start with Gatsby, make sure you have <a href="https://www.gatsbyjs.com/docs/quick-start/" rel="noopener noreferrer" target="_blank"><strong>Gatsby’s CLI installed on your machine</strong></a>. Once you have it, run the following commands in your terminal to create a new project and start the default application:</p>
<figure class="code"><figcaption>shell</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="shell"><code><span class="line"><span style="color:#EDCC95">$</span><span style="color:#97CCAE"> gatsby</span><span style="color:#97CCAE"> new</span><span style="color:#97CCAE"> faang-variation</span></span>
<span class="line"><span style="color:#EDCC95">$</span><span style="color:#97CCAE"> cd</span><span style="color:#97CCAE"> faang-variation</span></span>
<span class="line"><span style="color:#EDCC95">$</span><span style="color:#97CCAE"> gatsby</span><span style="color:#97CCAE"> develop</span></span></code></pre></figure>
<p>Go to <a href="http://localhost:8000/" rel="noopener noreferrer" target="_blank"><strong>http://localhost:8000/</strong></a> and check that the app is up and running.</p>
<h3 id="step-2-fetching-data-from-the-api">Step 2: Fetching data from the API</h3>
<p>A server-side rendered application will typically fetch information from multiple sources. Today, we are going to use Yahoo Finance’s API to achieve our goal. The <a href="https://www.npmjs.com/package/yahoo-finance" rel="noopener noreferrer" target="_blank"><strong>yahoo-finance</strong></a> module is all we need:</p>
<figure class="code"><figcaption>shell</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="shell"><code><span class="line"><span style="color:#EDCC95">$</span><span style="color:#97CCAE"> yarn</span><span style="color:#97CCAE"> add</span><span style="color:#97CCAE"> yahoo-finance</span></span></code></pre></figure>
<p>With the module installed, it’s time to edit <em>gatsby-node.js</em>. <a href="https://www.gatsbyjs.com/docs/reference/config-files/gatsby-node/" rel="noopener noreferrer" target="_blank"><strong>Gatsby Node API</strong></a> is an interface provided by Gatsby that allows us to dynamically generate static pages, which is precisely what we need.</p>
<p>Add the following to your <a href="https://github.com/rafaelquintanilha/faang-variation/blob/master/gatsby-node.js" rel="noopener noreferrer" target="_blank"><strong>gatsby-node.js</strong></a>:</p>
<figure class="code"><figcaption>javascript</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="javascript"><code><span class="line"><span style="color:#A1C1E4">const</span><span style="color:#ECEBE8"> yf </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> require</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">"yahoo-finance"</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#ECEBE8"> path </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> require</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">`path`</span><span style="color:#ECEBE8">)</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">exports</span><span style="color:#ECEBE8">.</span><span style="color:#EDCC95">createPages</span><span style="color:#A1C1E4"> =</span><span style="color:#A1C1E4"> async</span><span style="color:#ECEBE8"> ({ actions: { createPage } }) </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4"> const</span><span style="color:#ECEBE8"> homePageTemplate </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> path.resolve</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">`src/components/Home.js`</span><span style="color:#ECEBE8">)</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4"> const</span><span style="color:#ECEBE8"> symbols </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> [</span><span style="color:#97CCAE">"FB"</span><span style="color:#ECEBE8">, </span><span style="color:#97CCAE">"AMZN"</span><span style="color:#ECEBE8">, </span><span style="color:#97CCAE">"AAPL"</span><span style="color:#ECEBE8">, </span><span style="color:#97CCAE">"NFLX"</span><span style="color:#ECEBE8">, </span><span style="color:#97CCAE">"GOOG"</span><span style="color:#ECEBE8">]</span></span>
<span class="line"><span style="color:#A1C1E4"> const</span><span style="color:#ECEBE8"> prices </span><span style="color:#A1C1E4">=</span><span style="color:#A1C1E4"> await</span><span style="color:#EDCC95"> yf.quote</span><span style="color:#ECEBE8">({</span></span>
<span class="line"><span style="color:#ECEBE8">   symbols,</span></span>
<span class="line"><span style="color:#ECEBE8">   modules: [</span><span style="color:#97CCAE">"price"</span><span style="color:#ECEBE8">],</span></span>
<span class="line"><span style="color:#ECEBE8"> })</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4"> const</span><span style="color:#ECEBE8"> buildTime </span><span style="color:#A1C1E4">=</span><span style="color:#A1C1E4"> new</span><span style="color:#EDCC95"> Date</span><span style="color:#ECEBE8">()</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95"> createPage</span><span style="color:#ECEBE8">({</span></span>
<span class="line"><span style="color:#ECEBE8">   path: </span><span style="color:#97CCAE">`/`</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#ECEBE8">   component: homePageTemplate,</span></span>
<span class="line"><span style="color:#ECEBE8">   context: {</span></span>
<span class="line"><span style="color:#ECEBE8">     prices,</span></span>
<span class="line"><span style="color:#ECEBE8">     buildTime,</span></span>
<span class="line"><span style="color:#ECEBE8">   },</span></span>
<span class="line"><span style="color:#ECEBE8"> })</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span></code></pre></figure>
<p>The code should be very straightforward: we are quoting prices for our desired stocks and recording the build time. Next, we use the <a href="https://www.gatsbyjs.com/docs/reference/config-files/gatsby-node/#createPages" rel="noopener noreferrer" target="_blank"><strong>createPage function</strong></a> to generate our home page using the Home component at <a href="https://github.com/rafaelquintanilha/faang-variation/blob/master/src/components/Home.js" rel="noopener noreferrer" target="_blank"><em><strong>src/components/Home.js</strong></em></a> as a template.</p>
<h3 id="step-3-create-the-home-component">Step 3: Create the Home component</h3>
<p>Now that we already have the stock information available at build time in Gatsby, the final piece of the app is to actually create the Home component, which we will use to render the content based on data.</p>
<p>Go ahead and delete the <em>pages</em> folder, which has a static <em>index.js</em> file that we won’t be using. Then, create <em>Home.js</em> in <em>src/components</em> and add the following:</p>
<figure class="code"><figcaption>javascript</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="javascript"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> React </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> "react"</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> Home</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> ({ pageContext: { prices, buildTime } }) </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  return</span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">    /* Code here */</span></span>
<span class="line"><span style="color:#ECEBE8">  )</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">export</span><span style="color:#A1C1E4"> default</span><span style="color:#ECEBE8"> Home</span></span></code></pre></figure>
<p>The actual UI is not relevant. What really matters is that you can access the prices and buildTime variables generated in the previous step, using the pageContext prop of the component.</p>
<p>If you copy the code from GitHub and start the server again, you should be able to see our simple app up and running!</p>
<figure class="image"><img alt="FAANG Stock Price Variation Website" loading="lazy" decoding="async" width="611" height="379" src="https://rafaelquintanilha.com/_astro/image--25-.BIEZUyoB_v091U.webp"><figcaption>FAANG Stock Price Variation Website</figcaption></figure>
<h3 id="step-4-deploy-to-netlify">Step 4: Deploy to Netlify</h3>
<p>For this step, I am assuming you have your code hosted on a GitHub repository. Our app is ready, so it’s time to make it available to the world.</p>
<p>Make sure you have already signed up to Netlify. After this is done, go to <a href="https://app.netlify.com/start" rel="noopener noreferrer" target="_blank"><strong>https://app.netlify.com/start</strong></a> in order to connect your GitHub repository.</p>
<figure class="image"><img alt="Create a new site in Netlify" loading="lazy" decoding="async" width="615" height="470" src="https://rafaelquintanilha.com/_astro/image--26-.kZiCZFUo_ZmNbDn.webp"><figcaption>Create a new site in Netlify</figcaption></figure>
<p>Click on “GitHub” and authorize the integration. Next, select your repo and proceed to deploy:</p>
<figure class="image"><img alt="Configure site settings" loading="lazy" decoding="async" width="569" height="473" src="https://rafaelquintanilha.com/_astro/image--27-.Bp6MzxqY_LyLH6.webp"><figcaption>Configure site settings</figcaption></figure>
<p>It’s that simple. In a few minutes, your website will be available. Change the domain name if you want and it’s done! The live result <a href="https://faangvariation.netlify.app/" rel="noopener noreferrer" target="_blank"><strong>can be seen here</strong></a>.</p>
<h3 id="step-5-add-build-hook">Step 5: Add build hook</h3>
<p>The ultimate goal of today’s article is to set up a cron job that will trigger a build every weekday at 8 pm UTC. As discussed before, first we need to get a unique URL to which we will issue a POST request.</p>
<p>Go to Netlify > Site settings, then select “Build &#x26; deploy” and scroll to “Build hooks.” Click to add a new hook and fill it up with some descriptive information:</p>
<figure class="image"><img alt="Add Build hooks" loading="lazy" decoding="async" width="594" height="379" src="https://rafaelquintanilha.com/_astro/image--28-.d2hQ3XDT_1Lgcts.webp"><figcaption>Add Build hooks</figcaption></figure>
<p>After you save it, a unique URL will be available to you.</p>
<h3 id="step-6-schedule-curl-requests-with-github-actions">Step 6: Schedule cURL requests with GitHub Actions</h3>
<p>Finally, we are ready to integrate with GitHub Actions in order to schedule the builds. But before we jump into that, let’s make sure the build hook is working.</p>
<p>Open your terminal and run the following command, replacing BUILD_HOOK_URL with the URL you generated before.</p>
<figure class="code"><figcaption>shell</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="shell"><code><span class="line"><span style="color:#EDCC95">$</span><span style="color:#97CCAE"> curl</span><span style="color:#97CCAE"> -X</span><span style="color:#97CCAE"> POST</span><span style="color:#97CCAE"> -d</span><span style="color:#97CCAE"> {}</span><span style="color:#97CCAE"> BUILD_HOOK_URL</span></span></code></pre></figure>
<p>Go back to <em>Site overview</em> in Netlify and make sure you see something like this:</p>
<figure class="image"><img alt="Deploys in Netlify" loading="lazy" decoding="async" width="577" height="227" src="https://rafaelquintanilha.com/_astro/image--29-.DMz9a4EI_qDDX.webp"><figcaption>Deploys in Netlify</figcaption></figure>
<p>The hook is working! Now go to your GitHub repository, click on “Actions” and then on “set up a workflow yourself”.</p>
<figure class="image"><img alt="Configuring GitHub Actions" loading="lazy" decoding="async" width="618" height="438" src="https://rafaelquintanilha.com/_astro/image--30-.GUyTTXQb_ZMh2wz.webp"><figcaption>Configuring GitHub Actions</figcaption></figure>
<p>Finally, get rid of everything on the left side editor and add the following (again, replace BUILD_HOOK_URL with your own):</p>
<figure class="code"><figcaption>yaml</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="yaml"><code><span class="line"><span style="color:#A1C1E4">name</span><span style="color:#ECEBE8">: </span><span style="color:#97CCAE">Trigger Netlify Build</span></span>
<span class="line"><span style="color:#A1C1E4">on</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#A1C1E4">  schedule</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">    # “At 20:00 on every day-of-week from Monday through Friday.”</span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">    # https://crontab.guru/#0_20_*_*_1-5</span></span>
<span class="line"><span style="color:#ECEBE8">    - </span><span style="color:#A1C1E4">cron</span><span style="color:#ECEBE8">: </span><span style="color:#97CCAE">'0 20 * * 1-5'</span></span>
<span class="line"><span style="color:#A1C1E4">jobs</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#A1C1E4">  build</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#A1C1E4">    name</span><span style="color:#ECEBE8">: </span><span style="color:#97CCAE">Build Hook</span></span>
<span class="line"><span style="color:#A1C1E4">    runs-on</span><span style="color:#ECEBE8">: </span><span style="color:#97CCAE">ubuntu-latest</span></span>
<span class="line"><span style="color:#A1C1E4">    steps</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#ECEBE8">      - </span><span style="color:#A1C1E4">name</span><span style="color:#ECEBE8">: </span><span style="color:#97CCAE">Curl request</span></span>
<span class="line"><span style="color:#A1C1E4">        run</span><span style="color:#ECEBE8">: </span><span style="color:#97CCAE">curl -X POST -d {} BUILD_HOOK_URL</span></span></code></pre></figure>
<p>Commit your changes and that’s it! You have now learned how to edit cron jobs in order to schedule builds for your static application.</p>
<h2 id="final-thoughts"><strong>Final thoughts</strong></h2>
<p>Static sites are very fast and <a href="https://buttercms.com/kb/seo-optimization" rel="noopener noreferrer" target="_blank"><strong>great for SEO</strong></a>, which makes them very appealing when designing your application. However, those benefits come with drawbacks, especially if you want data to be regularly updated.</p>
<p>Scheduling cron jobs is a viable solution assuming that you can afford some delay when triggering your rebuilds. Note that the smaller the delay, the more builds will run, and the more expensive it will be for you to adopt this strategy (however, most services will provide you some kind of free tier if you want to test it out).</p>
<p>This approach is very useful if you use a <a href="https://buttercms.com/blog/what-is-headless-cms/" rel="noopener noreferrer" target="_blank"><strong>headless CMS</strong></a> such as ButterCMS with a javascript framework like React. Consider this strategy to regularly update the content on your page!</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[React SEO: How to Build Search-Friendly Pages in React]]></title>
<description><![CDATA[How to boost your React app SEO ranking with many practical tips.]]></description>
<link>https://rafaelquintanilha.com/react-seo-how-to-build-search-friendly-pages-in-react/</link>
<guid isPermaLink="false">6383abfb14168e003dd8f748</guid>
<category><![CDATA[React]]></category><category><![CDATA[SEO]]></category><category><![CDATA[Best Practices]]></category><category><![CDATA[ButterCMS]]></category>
<dc:creator><![CDATA[Rafael Quintanilha]]></dc:creator>
<pubDate>Thu, 21 Jan 2021 18:27:00 GMT</pubDate>

<content:encoded><![CDATA[<p>Digital advertising is a multi-billionaire industry that has been rising sharply. In fact, the money spent worldwide on it has <a href="https://www.statista.com/statistics/237974/online-advertising-spending-worldwide/" rel="noopener noreferrer" target="_blank"><strong>nearly doubled</strong></a> since 2016. The motive for this is clear: companies want to be seen on the Internet.</p>
<p>On the one hand, you can pay a large number of dollars to have your ad featured; on the other hand, you can be seen for free. That’s due to SEO, or Search Engine Optimization. Attracting organic traffic to your website is one of the most profitable actions a business can take, and this is by no means a trivial thing to achieve.</p>
<p>In this article, I’ll guide you on how to build SEO-friendly pages using React, the most popular framework for building modern websites. I'll also show you how these methods can be applied to dynamic content with the help of a <a href="https://buttercms.com/react-cms/" rel="noopener noreferrer" target="_blank"><strong>good React CMS</strong></a>.</p>
<h2 id="the-importance-of-seo"><strong>The Importance of SEO</strong></h2>
<p>Google owns 92% of the search engine market share worldwide and this number has been fairly <a href="https://gs.statcounter.com/search-engine-market-share#yearly-2009-2020" rel="noopener noreferrer" target="_blank"><strong>steady since 2009</strong></a>. It makes sense, then, to target Google and what it considers good practice when developing your SEO strategy.</p>
<figure class="image"><img alt="Search Engine Market Share (2020)" loading="lazy" decoding="async" width="1200" height="628" src="https://rafaelquintanilha.com/_astro/react-seo-search-engine-market-share.iKYtaES7_ZePX6C.webp"><figcaption>Search Engine Market Share (2020)</figcaption></figure>
<p>The core concept is that the higher your website ranks on the Search Results Page (SERP), the higher the likelihood that users will click on it. While this is fairly intuitive, what might surprise you is how large the gap is in click-through rates (CTR) in the first positions — <a href="https://www.smartinsights.com/search-engine-optimisation-seo/seo-analytics/comparison-of-google-clickthrough-rates-by-position/" rel="noopener noreferrer" target="_blank"><strong>recent studies</strong></a> have found that the combined click-through rates for positions 1 and 2 on a SERP are approximately double the combined click-through rates for positions 3 and 4! In other words, your effectiveness in being seen is exponentially affected by how well you fare on the results page.</p>
<h2 id="how-google-ranks-your-website"><strong>How Google Ranks Your Website</strong></h2>
<p>Before we learn how to enhance React SEO, we must understand how the process works. Simply put, Google uses a bot called Googlebot (how creative!) to crawl your application. This robot is called a <em>web crawler</em>.</p>
<p>The crawler will load your application, analyze it, and rank it by a set number of criteria. While exactly how each criterion is evaluated is unknown, one should target as many features as possible. An application optimized for SEO will enforce some rules to increase the likelihood of being highly ranked.</p>
<figure class="image"><img alt="Meta tags" loading="lazy" decoding="async" width="1146" height="584" src="https://rafaelquintanilha.com/_astro/react-seo-meta-tags.zMQ_VCok_Z2vb5iD.webp"><figcaption>Meta tags</figcaption></figure>
<h3 id="crawling-budget">Crawling Budget</h3>
<p>We live in an era of limited resources, and this will always be true. The same concept applies to search engines and their crawlers — they need to spend their time wisely. The result of this policy is what is called a <em>crawling budget</em>, or how much time a crawler will spend analyzing your website. As you might guess, how efficiently Google will parse your application is severely impacted by your app speed. Any effort to improve load time is welcome, which can become a problem for React apps.</p>
<h3 id="accessible-urls">Accessible URLs</h3>
<p>It is imperative for React SEO to have an SEO-friendly URL. In Google’s words: <em>“URLs with words that are relevant to your site's content and structure are friendlier for visitors navigating your site.”</em> The full set of <a href="https://developers.google.com/search/docs/beginner/seo-starter-guide?hl=en&#x26;visit_id=637438582413772187-2328543862&#x26;rd=1#best-practices_6" rel="noopener noreferrer" target="_blank"><strong>best practices can be seen here</strong></a>. This factor turns out to be one of the major problems with Single Page Applications (SPA), such as regular React applications. Once SPAs are evaluated on the client side, the whole application can live within a single URL.</p>
<p>Several other factors affect React SEO. However, the above are the most flagrant shortcomings of a React application and will be the object of discussion for the next sections.</p>
<h2 id="react-seo-the-problem-with-react-applications"><strong>React SEO: The Problem with React Applications</strong></h2>
<p>So far we have learned that search engines use robots called crawlers to parse your website and rank them accordingly in their SERP. Unfortunately, several of the aspects that are valuable to search engines are not found in standard React applications. We will now analyze what exactly React’s limitations are and, later on, learn how we can overcome them.</p>
<h3 id="static-vs-dynamic-sites">Static vs Dynamic Sites</h3>
<p>Back in the day, all web pages were called <em>static.</em> The process is as follows: the user makes a request to a server for a given URL. The server then returns a set of HTML, JavaScript, and CSS files that are served on-demand and rendered on the user’s browser.</p>
<p>This old-fashioned process is ideal for robots — they have all assets for that web page when they access it. However, things changed and web applications became more complex. The content is many times <em>dynamic</em>, meaning that it changes constantly. Think about your Twitter feed: all content is in constant motion, even though the URL remains the same.</p>
<p>Dynamic content is a problem for crawlers once the data might not be available during their crawling time (remember the crawling budget?). Also, it is loaded via JavaScript, meaning the browser needs to <em>render</em> and <em>parse</em> the code before anyone can see anything. This substantially increases the time a crawler needs to parse the content, hence affecting your SEO.</p>
<h3 id="how-spas-work">How SPAs Work</h3>
<p>As mentioned before, React is a Single Page Application. This means that your whole app lives on a single page, even though you can simulate different routes and pages.</p>
<p>While SPAs are very convenient for dynamic applications, they lack good SEO support. For starters, if all you have is a single page, your meta tags will hardly describe accurately each part of your application. Moreover, you won’t be able to generate unique URLs out-of-the-box, resorting to a <em>client-side routing</em> library like <a href="https://reactrouter.com/" rel="noopener noreferrer" target="_blank"><strong>react-router</strong></a>.</p>
<p>And finally, an SPA is a single webpage where JavaScript is responsible for updating the content on the screen. That usually means that the JavaScript code is bulky, which leads to a higher parse time by the browser. Ultimately, your application will load slower (due to the time needed to download + parse a larger JavaScript file) and your crawling budget will run out quickly.</p>
<p>It all looks like React applications are doomed to rot on the dark corners of the SERP, but it doesn’t need to be that way. Next, we will learn how to overcome the aforementioned issues.</p>
<h2 id="server-side-rendering"><strong>Server-Side Rendering</strong></h2>
<p>Server-side rendering (SSR), also known as <em>isomorphic applications</em>, is a clever solution to the SPAs shortcomings.</p>
<p>In order to avoid the single page with bulky JavaScript, the React community evolved to a model where the application is rendered on the server during <em>build time</em>. That means that instead of sending a large JavaScript file to the client and letting it figure out what to render, a compiler will analyze the code on the server and generate multiple pages. These pages will then be served on their specific routes, in the good ol’ static website model.</p>
<p>The advantage of such a model is that you can keep working with a cutting-edge library such as React and still retain the biggest advantage of static websites — blazing-fast load times!</p>
<p>However, it is a product decision to understand if SSR is ideal for your project. As a rule of thumb, if your application has content that changes <em>too</em> often, client-side applications should be the best option. Now, if your content is mostly static, and you have many web pages that would benefit from being found on a search engine (such as a product landing page or a blog post), SSR is the way to go.</p>
<h2 id="implementing-an-ssr-application-in-react"><strong>Implementing an SSR Application in React</strong></h2>
<p>The most famous frameworks for developing SSR applications are <a href="http://gatsbyjs.com/" rel="noopener noreferrer" target="_blank"><strong>Gatsby</strong></a> and <a href="https://nextjs.org/" rel="noopener noreferrer" target="_blank"><strong>Next.js</strong></a>. Although there are differences between them, their main goal is similar: to allow next-generation web applications to remain blazing-fast.</p>
<p>It is beyond the scope of this article to compare both technologies, but I will use Gatsby as an example of how the framework addresses the React SEO dilemma.</p>
<h3 id="react-helmet">React-helmet</h3>
<p><a href="https://github.com/nfl/react-helmet" rel="noopener noreferrer" target="_blank"><strong>React-helmet</strong></a> is the industry standard for meta tags optimization. It allows every page to have its own custom meta tags, what we have seen is a major victory for React SEO. The library also allows for the addition of <a href="https://ogp.me/" rel="noopener noreferrer" target="_blank"><strong>Open Graph</strong></a>, which directly impacts the shareability of your content on potentially highly viral spaces such as social networks.</p>
<figure class="image"><img alt="React Helmet SEO plugin" loading="lazy" decoding="async" width="906" height="309" src="https://rafaelquintanilha.com/_astro/react-helmet-react-seo-plugin.DD9nj6S2_Z1fHjqM.webp"><figcaption>React Helmet SEO plugin</figcaption></figure>
<p>Fortunately, Gatsby provides a wide set of plugins that can be used to simplify your life as a developer. The <a href="https://www.gatsbyjs.com/plugins/gatsby-plugin-react-helmet/" rel="noopener noreferrer" target="_blank"><strong>gatsby-plugin-react-helmet</strong></a> repository is one of the most used and widely maintained plugins in the ecosystem.</p>
<p>If you haven’t tried it already, <a href="https://www.gatsbyjs.com/tutorial/seo-and-social-sharing-cards-tutorial/#reach-skip-nav" rel="noopener noreferrer" target="_blank"><strong>this comprehensive tutorial</strong></a> will help you get up on your feet with Gatsby and react-helmet.</p>
<h3 id="gatsby-image">Gatsby-image</h3>
<p>We have repeatedly insisted on how harmful to your React SEO score large JavaScript files are. However, I have never found a potential performance threat as strong as images.</p>
<p>Developers often optimize too much of what is in their control — dependencies, code splitting, etc. But many overlook that a large image loaded on your website can severely impact its performance. While code is under control, static assets are often not. They are provided by content creators, marketers, authors, and others. Therefore, we need a plan to mitigate the potential impacts.</p>
<p>My favorite solution for this problem is <a href="https://www.gatsbyjs.com/plugins/gatsby-image/" rel="noopener noreferrer" target="_blank"><strong>gatsby-image</strong></a>, another plugin meant to save your life. Gatsby-image takes care of, among several other things, optimizing your images and serving them in the most efficient and responsive format. It enhances the look and feel of your app, not to mention the performance and ultimate SEO gain.</p>
<h3 id="other-plugins">Other Plugins</h3>
<p>Gatsby has a <a href="https://www.gatsbyjs.com/plugins" rel="noopener noreferrer" target="_blank"><strong>vast library of plugins</strong></a>. Many of them are zero-config, meaning that you gain React SEO without much more effort than an <em>npm install</em>. As an example, <a href="https://www.gatsbyjs.com/plugins/gatsby-plugin-sitemap" rel="noopener noreferrer" target="_blank"><strong>gatsby-plugin-sitemap</strong></a> will generate sitemaps for your web page, helping bots to crawl your content in the right way.</p>
<figure class="image"><img alt="Gatsby Plugin Library" loading="lazy" decoding="async" width="1228" height="767" src="https://rafaelquintanilha.com/_astro/gatsby-plugin-library.lIQC1Oxu_1n8NW8.webp"><figcaption>Gatsby Plugin Library</figcaption></figure>
<h3 id="route-based-code-splitting">Route-based Code Splitting</h3>
<p>Another great feature of Gatsby is the ability to serve static pages in their own URL (thus addressing the <em>Accessible URLs</em> point) and be wise about what should be included in that particular page.</p>
<p>Remember how SPAs are penalized by having large chunks of JavaScript being loaded at all times? With route-based code splitting, the only JavaScript code sent from the server to the client will be necessary to render whatever is on that particular page. <a href="https://www.gatsbyjs.com/blog/2019-04-02-behind-the-scenes-what-makes-gatsby-great/#route-based-code-splitting" rel="noopener noreferrer" target="_blank"><strong>The following article describes in detail</strong></a> how it works.</p>
<h3 id="do-i-need-a-static-site-generator">Do I Need a Static Site Generator?</h3>
<p>By all means, every advantage listed in the previous topics can be achieved with vanilla JavaScript and other tools. However, <a href="https://buttercms.com/blog/6-of-the-best-static-site-generators-in-2020/" rel="noopener noreferrer" target="_blank"><strong>SSGs like Gatsby and Next.js</strong></a> will abstract the hassle from you to the point that the standard Gatsby application is born with a 100 SEO score on <a href="https://developers.google.com/web/tools/lighthouse" rel="noopener noreferrer" target="_blank"><strong>Lighthouse</strong></a>, Google’s performance analyzer.</p>
<p>More than recommending framework A or B, the goal of this post is to outline the importance of SEO, the shortcomings of barebone React applications, and which tools can be used to overcome them. Don’t feel pressured to switch and adopt a new technology tomorrow — but be aware that different businesses have different needs and it is your job to find the right tool.</p>
<h2 id="static-sites-can-be-dynamic"><strong>Static Sites Can Be Dynamic</strong></h2>
<p>The last point worth mentioning is that, in fact, static sites can have dynamic content. Yes, I know I said before that they are two different kinds of applications, but bear with me for a moment.</p>
<p>If you opt for a Server Side Rendering strategy, your deployment process will include a <em>building time</em>. During this period, the framework will fetch the most up-to-date data available and construct the static page. That means that the <em>source</em> of data can constantly be changing!</p>
<p>This ends up being one of the main advantages of such a process, given that it allows the leverage of a <a href="https://buttercms.com/blog/what-is-headless-cms/" rel="noopener noreferrer" target="_blank"><em><strong>headless CMS</strong></em></a> such as ButterCMS. Using this strategy, you can have your Gatsby application connected to ButterCMS and fetch all content from an external admin panel. The main advantage is the possibility to offload the need to constantly edit static content onto professionals better suited for such actions, like marketers and copywriters.</p>
<p>Every time a change is made to static content, or in defined intervals, a new build will be triggered, and once it is finished your content will be updated. The process is highly SEO-friendly and, when properly designed, will allow content creators to choose the best features for the web crawler carefully.</p>
<p>ButterCMS is a leading <a href="https://buttercms.com/gatsbyjs-cms/" rel="noopener noreferrer" target="_blank"><strong>Gatsby CMS</strong></a>, and you can set up the integration with your Gatsby application in minutes!</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[Create a Serverless React Application]]></title>
<description><![CDATA[Let us understand what serverless really means, what's good about it and how you can take advantage of this architecture when building React apps.]]></description>
<link>https://rafaelquintanilha.com/create-a-serverless-react-application/</link>
<guid isPermaLink="false">6370603342a473003d9dcb24</guid>
<category><![CDATA[React]]></category><category><![CDATA[ButterCMS]]></category><category><![CDATA[Netlify]]></category>
<dc:creator><![CDATA[Rafael Quintanilha]]></dc:creator>
<pubDate>Wed, 31 Jul 2019 03:00:00 GMT</pubDate>

<content:encoded><![CDATA[<p>In the world of software development, sometimes it might be hard to keep up with all the new trends and buzzwords. Developers love new things, so it’s understandable that preferences and approaches change over time, although it might happen overwhelmingly quickly.</p>
<p>One of the latest buzzwords to become popular is serverless. Somehow, it seems to be everywhere now, empowering the newest startups as well as the tech giants. But what is serverless after all? Is it worth knowing?</p>
<p>In this article, I will guide you through learning what serverless really is, the reason why it is so powerful and give you some heuristics to help you decide if serverless is well suited for your project. Later, we will build a simple serverless app using <a href="https://www.netlify.com/" rel="noopener noreferrer" target="_blank">Netlify</a> and <a href="https://buttercms.com" rel="noopener noreferrer" target="_blank">ButterCMS</a> to help you better understand the concepts explained throughout the text.</p>
<p>So what is serverless?</p>
<h2 id="the-serverless-architecture">The Serverless Architecture</h2>
<p>The first and maybe unexpected thing you need to know about serverless is that it <em>actually</em> has servers. Although it might sound contradictory, this is relieving once you need to keep your back-end separated from the client. Why do we call it “serverless” then?</p>
<p>The main difference between <em>serverless</em> and <em>serverful</em> applications is that for serverless applications, the servers management is taken care of for you. That means they still exist and function as designed, but you are free from the maintenance burden. By “burden” I mean managing availability, scalability, redundancy, uptime, orchestration, and all many other things that are important to modern web applications.</p>
<p>Before digging deeper into our definition, let us first understand why serverless emerged in the first place.</p>
<h3 id="the-motivation-behind-serverless">The motivation behind serverless</h3>
<p>Not long ago, applications ran locally in private-owned data centers. This changed when cloud computing became popular, smashing costs and enabling developers and companies to move their infrastructure to the web and focus on their products instead. Companies such as Amazon specialized in developing reliable and distributed data centers that could be accessed anywhere in the world at the same time.</p>
<p>Although this was a turning point for software development, it also brought a new set of problems to be solved ⁠— make sure the server is available at any time, scale up its capacity based on a surge in demand (and conversely scale down during peaceful times), dynamically allocate memory to the most sensitive processes, and so on.</p>
<p>What in the beginning was supposed to be an infrastructure relief ended up becoming a headache once more. Therefore, the demand for headache-free software development was still around (and will likely stay around for as long as software developers live). How do you keep the improvements brought by cloud computing <em>without</em> spending too much time managing the cloud?</p>
<p>The answer is, of course, serverless.</p>
<h3 id="what-is-serverless">What is serverless?</h3>
<p>I mentioned that serverless architecture, in fact, uses servers, but that they are concealed from you. This is still a loose definition, so it’s time to go deeper into this.</p>
<p>The truth is that the definition of serverless varies a lot, some very technical, which can be confusing to newcomers. I’ll start by defining serverless as <em>architecture</em> or <em>methodology</em>. Finally, simply put, <strong>serverless architecture is when you perform computations without having to think about machine resource allocation</strong>. That is, the perks of cloud computing are seamlessly integrated into your workflow.</p>
<p>A more technical definition would be the following:</p>
<blockquote>
<p>Serverless is an event-driven, ephemeral and stateless cloud-based architecture that dynamically allocates machine resources.</p>
</blockquote>
<h3 id="lambda-functions">Lambda functions</h3>
<p>It all sounds too good to be true, but what is underneath a serverless architecture? The key is what we call a <em>lambda function</em>.</p>
<p>A <em>lambda function</em> is simply an anonymous function. Consider this JavaScript example:</p>
<figure class="code"><figcaption>js</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="js"><code><span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> multiplyBy</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> x </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  return</span><span style="color:#ECEBE8"> y </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> x </span><span style="color:#A1C1E4">*</span><span style="color:#ECEBE8"> y</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#ECEBE8"> triple </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> multiplyBy</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">3</span><span style="color:#ECEBE8">)</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">triple</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">10</span><span style="color:#ECEBE8">) </span><span style="color:#A7A49E;font-style:italic">// returns 30</span></span></code></pre></figure>
<p>Notice that the original function, <code>multiplyBy</code>, returns an (anonymous) function. This function has the original value passed to <code>mutiplyBy</code> in its scope, what we call closure.</p>
<p>In a serverless application, Lambda functions are invoked, perform the desired operation, and vanish (that’s why serverless is <em>ephemeral</em>). This process is handled by the serverless provider, the most famous being <a href="https://aws.amazon.com/lambda/" rel="noopener noreferrer" target="_blank">AWS Lambda</a>. In the end, all you need to do is to write your function and let the provider call it when it’s time (hence, <em>event-based</em>) while doing all machine allocation. Because you don’t control the environment where your code is running, you need to assume a <em>stateless</em> function, i.e., there is no data persistence in between calls.</p>
<figure class="image"><img alt="Lambda function diagram" loading="lazy" decoding="async" width="2100" height="1080" src="https://rafaelquintanilha.com/_astro/lambda-function.S549XHcR_zmDOv.webp"><figcaption>Lambda function diagram</figcaption></figure>
<p>So far we have finally learned <em>what</em> serverless is, conceptually and technically. Next, we will see <em>why</em> it is important.</p>
<h2 id="why-serverless-a-look-at-what-problems-it-solves">Why Serverless? A look at what problems it solves</h2>
<p>When developing an application, your prime goal is to focus on the problem you are trying to solve. Ultimately, it means that all work you need to do that is not directly linked to your goal needs to be minimized or, better, eliminated.</p>
<p>If there is a surge in the usage of your app, ideally it shouldn’t make any difference to your users. In reality, though, they might expect slowness, a drop in responsiveness and even no service at all if your server crashes. In order to prevent scenarios like this, you need to invest in good infrastructure. Unfortunately, maintaining such a robust infrastructure is time-consuming and expensive.</p>
<p>How can serverless help you with this dilemma?</p>
<h3 id="scales-out-of-the-box">Scales out-of-the-box</h3>
<p>Going serverless means that you are offsetting the responsibility of keeping your application stable regardless of the number of users to the service provider. This peace of mind can be hugely beneficial, not only because of the less amount of work but also because of the certainty that your app is going to behave well even in tail scenarios.</p>
<h3 id="active-upon-actual-usage">Active upon actual usage</h3>
<p>When you assume the responsibility of maintaining a server, you pay for the (virtual) machine you use. That gives you the freedom to control the server and use it however you see fit. Nonetheless, it comes for a price: you pay for that machine even if you are not using. So if your application is only accessed in specific periods of time, you might end up wasting money. Suppose that you have a certificate service that issues certificates to students upon the completion of a course. If the course is still ongoing, there’s no reason to keep the server up, yet you will need to. But in a serverless approach, every request will call a function that will directly impact your bill. This way, when there are no requests there is also no need to pay.</p>
<h3 id="cloud-lock-ins-vs-employee-lock-ins">Cloud lock-ins vs employee lock-ins</h3>
<p>If you want top-quality infrastructure management, you will need to assemble a DevOps team. That by itself will start to get expensive, but that’s not the worst of it. The main problem is that <em>changing personnel is way more difficult than changing a cloud provider</em>. So if you decide to switch technologies or are not satisfied with the current status of your company’s infrastructure, you will likely have a hard time. However, by adopting a serverless strategy, if you ever need to change providers you can expect a less painful experience.</p>
<h3 id="developer-experience">Developer experience</h3>
<p>It goes without saying that developers… well, like to develop. If you take from them the responsibility to overlook the infrastructure, they will get more productive by keeping their eyes on the end goal, i.e., creating an awesome app. A stressful working environment can kill devs productivity and actual care for their well being will bring you collateral improvements.</p>
<p>Now that we have seen some of the benefits of a serverless approach, let us check when it might make sense to you.</p>
<h2 id="when-to-use-a-serverless-architecture">When to use a Serverless Architecture?</h2>
<p>Granted, serverless brings a lot of joy back to development and can be a pretty useful resource. However, if you want to adopt this methodology, it’s indispensable that you know why and if it does help you, and avoid just following the hype.</p>
<p>So, what are some indicators that serverless is a good choice for you?</p>
<h3 id="little-control-over-your-server">Little control over your server</h3>
<p>Serverless diminishes your maintenance overhead because you do not own a server anymore. That also means that you can’t do whatever you want, like installing different tools and languages. So if your service provider allows for NodeJS functions, you can’t simply install Python on it and write Django code. Always consider how much control you need.</p>
<h3 id="short-computations">Short computations</h3>
<p>Lambda functions are event-driven, which means that they are called when something happens (for example, when a user is created). Serverless providers will set a maximum time limit your function can run to avoid that a single call drains all machine’s memory. This limit will vary from provider to provider, but it is important that you realize that if your application performs long and expensive computations, going serverless may be a problem for you.</p>
<h3 id="small-throughput">Small throughput</h3>
<p>We have seen that one advantage of serverless is that you are billed per function request and not by uptime (like traditional hosts such as <a href="https://www.digitalocean.com/" rel="noopener noreferrer" target="_blank">DigitalOcean</a>). This was interesting in our previous certificate example, but may not be well suited for applications with high throughput, that is, with too many requests per second. Real-time applications that poll the server too much can rapidly increase the cost of your project. Note that it doesn’t necessarily mean that serverless is a bad idea, once all other advantages (even intangible ones, such as developer experience) might be worth the extra cost.</p>
<h3 id="no-data-persistence">No data persistence</h3>
<p>Because you don’t own the machine, you can’t assume you have access to any files in there either. That means that your Lambda function should be stateless. If your application doesn’t need to persist any state (e.g. save data), serverless becomes really powerful. However, that isn’t the case in most situations. But even when you need to persist data, there is still a silver lining – services like <a href="https://aws.amazon.com/dynamodb/" rel="noopener noreferrer" target="_blank">Amazon DynamoDB</a> and <a href="https://www.mongodb.com/cloud/atlas" rel="noopener noreferrer" target="_blank">MongoDB Atlas</a> allow you to save and retrieve data through an API.</p>
<h3 id="prototyping">Prototyping</h3>
<p>I avoided mentioning prototyping earlier because I wanted to emphasize that serverless is <em>production-ready</em>. Top companies are heavily investing in it and there is no reason you should avoid it because of production concerns. That being said, serverless is tremendously helpful when prototyping. Once a prototype or early-stage application has no need to bother with auto scale, high throughput, and other infrastructure particularities, going serverless can definitely help you with your MVP.</p>
<p>The topics above are good heuristics for you to ask when considering a serverless architecture. But aside from that, there are also plenty of common use-cases that benefit from being serverless:</p>
<ul>
<li>Creating an API to handle subscribing to a newsletter (e.g. integrating with <a href="https://mailchimp.com/" rel="noopener noreferrer" target="_blank">Mailchimp</a>);</li>
<li>Handling authorization (e.g. using <a href="https://www.netlify.com/docs/identity/" rel="noopener noreferrer" target="_blank">Netlify’s Identity</a>);</li>
<li>Sending emails (e.g. using <a href="https://sendgrid.com/" rel="noopener noreferrer" target="_blank">SendGrid</a>);</li>
<li>Building an API gateway to send SMS (e.g. using <a href="https://www.twilio.com/blog/a-how-to-send-text-messages-from-your-static-site-using-netlify-twilio-and-serverless-functions" rel="noopener noreferrer" target="_blank">Twilio</a>);</li>
<li>And even [playing Pokemon](<a href="https://pokeless-eu.rauchg.now.sh/" rel="noopener noreferrer" target="_blank">https://pokeless-eu.rauchg.now.sh/</a>! (Well, maybe not very common)</li>
</ul>
<p>I encourage you to check the <a href="https://functions.netlify.com/examples/" rel="noopener noreferrer" target="_blank">Netlify’s Function Examples</a> to get some inspiration of what you can achieve by adopting a serverless architecture.</p>
<p>We have covered serverless in great depth, by defining what it is, understanding why it can be useful and finally learning which situations can benefit the most from this methodology. Next, we will put the theory aside and learn how to create a serverless API in practice.</p>
<h2 id="serverless-in-practice-with-buttercms-and-netlify">Serverless in practice with ButterCMS and Netlify</h2>
<p>For the rest of this article, we will build a serverless API using Netlify which will fetch blog posts stored in <a href="https://buttercms.com/" rel="noopener noreferrer" target="_blank">ButterCMS</a>, the headless Content Management System, and group them by month. This is a simple feature but aims to show how you can leverage both Butter and serverless by doing computations in the back-end (and therefore increase the performance of your app). Notice that our application is stateless, once it doesn’t need to persist any data (it will always read from Butter’s API). Finally, we will build a simple front-end to exemplify how you could fetch this data in a real application.</p>
<h3 id="setting-up-the-project">Setting up the project</h3>
<p>Before we start, all code is in <a href="https://github.com/rafaelquintanilha/butter-serverless-example" rel="noopener noreferrer" target="_blank">this GitHub repo</a> and a simple demo can be accessed here.</p>
<p>Let’s start by creating a new repo using <a href="https://github.com/facebook/create-react-app" rel="noopener noreferrer" target="_blank">create-react-app</a>. If your npm version is 5.2 or higher, npx will be available to you. Otherwise, you can install create-react-app by running <code>npm install -g create-react-app</code>.</p>
<figure class="code"><figcaption>sh</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="sh"><code><span class="line"><span style="color:#EDCC95">npx</span><span style="color:#97CCAE"> create-react-app</span><span style="color:#97CCAE"> butter-serverless-example</span></span>
<span class="line"><span style="color:#EDCC95">cd</span><span style="color:#97CCAE"> butter-serverless-example</span></span></code></pre></figure>
<p>We will use the power of <a href="https://www.netlify.com/products/dev/" rel="noopener noreferrer" target="_blank">Netlify Dev</a> in this tutorial. Netlify Dev allows you to replicate Netlify’s environment in your machine. It means that you can develop locally as you are in production, inject env variables, share live URLs and much more. Let us explore what it can do for us.</p>
<p>If you haven’t already, install the Netlify CLI:</p>
<figure class="code"><figcaption>sh</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="sh"><code><span class="line"><span style="color:#EDCC95">npm</span><span style="color:#97CCAE"> install</span><span style="color:#97CCAE"> netlify-cli</span><span style="color:#97CCAE"> -g</span></span></code></pre></figure>
<p>Then make sure that you are logged in:</p>
<figure class="code"><figcaption>sh</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="sh"><code><span class="line"><span style="color:#EDCC95">netlify</span><span style="color:#97CCAE"> login</span></span></code></pre></figure>
<p>Once you are logged in, the next step is to link your folder to a Netlify project. Make sure you have your project created in Netlify. You can easily do that from the UI or use:</p>
<figure class="code"><figcaption>sh</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="sh"><code><span class="line"><span style="color:#EDCC95">netlify</span><span style="color:#97CCAE"> deploy</span></span></code></pre></figure>
<p>Whatever way you choose, it is pretty straightforward to get it done (I personally like to create a repo in GitHub and then create a new site in Netlify directly from Git). After this, run the following command to link your app:</p>
<figure class="code"><figcaption>sh</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="sh"><code><span class="line"><span style="color:#EDCC95">netlify</span><span style="color:#97CCAE"> link</span></span></code></pre></figure>
<p>If you have started your project from Git, the CLI will automatically recognize the address. If that’s not the case, you can provide your site’s name or ID in order to finish the process. Both information can be found on your project’s settings page.</p>
<h3 id="creating-your-first-function">Creating your first function</h3>
<p>Once the setup is done we can start by creating our first function. Functions need to live in a folder inside your app, so go ahead and create <code>src/functions</code> in your project.</p>
<p>Next, at the root of <code>butter-serverless-example</code> create Netlify’s configuration file <code>netlify.toml</code> and add the following:</p>
<figure class="code"><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="plaintext"><code><span class="line"><span>[build]</span></span>
<span class="line"><span>  functions = "src/functions"</span></span></code></pre></figure>
<p>Which basically points Netlify to the right folder.</p>
<p>Let us use the CLI to create our first function:</p>
<figure class="code"><figcaption>sh</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="sh"><code><span class="line"><span style="color:#EDCC95">netlify</span><span style="color:#97CCAE"> functions:create</span></span></code></pre></figure>
<p>Many examples will display. They give you an overview of the many possibilities you have with serverless functions. For this example, select the <code>hello-world</code> option and name it <code>posts-by-month</code>. After that, go check the functions folder and notice that <code>posts-by-month/posts-by-month.js</code> is there.</p>
<p>In order to test that everything is working as expected, run <code>netlify dev</code> and go to <a href="http://localhost:8888" rel="noopener noreferrer" target="_blank">http://localhost:8888</a>. The CRA default app will be there. But how do we test that our function is working?</p>
<p>Every function in Netlify is mapped to a specific URL <code>/.netlify/functions/&#x3C;function name></code>. Simply go to <a href="http://localhost:8888/.netlify/functions/posts-by-month" rel="noopener noreferrer" target="_blank">http://localhost:8888/.netlify/functions/posts-by-month</a> and check that everything works.</p>
<h3 id="fetching-from-butter">Fetching from Butter</h3>
<p>Our <code>posts-by-month.js</code> function currently only returns some dummy data. But before we fix that, let us examine closely what is going on:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">exports</span><span style="color:#ECEBE8">.</span><span style="color:#EDCC95">handler</span><span style="color:#A1C1E4"> =</span><span style="color:#A1C1E4"> async</span><span style="color:#ECEBE8"> (event, context) </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  try</span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">    const</span><span style="color:#ECEBE8"> subject </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> event.queryStringParameters.name </span><span style="color:#A1C1E4">||</span><span style="color:#97CCAE"> 'World'</span></span>
<span class="line"><span style="color:#A1C1E4">    return</span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#ECEBE8">      statusCode: </span><span style="color:#97CCAE">200</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#ECEBE8">      body: </span><span style="color:#EDCC95">JSON.stringify</span><span style="color:#ECEBE8">({ message: </span><span style="color:#97CCAE">`Hello ${</span><span style="color:#97CCAE">subject</span><span style="color:#97CCAE">}`</span><span style="color:#ECEBE8"> }),</span></span>
<span class="line"><span style="color:#ECEBE8">    }</span></span>
<span class="line"><span style="color:#ECEBE8">  } </span><span style="color:#A1C1E4">catch</span><span style="color:#ECEBE8"> (err) {</span></span>
<span class="line"><span style="color:#A1C1E4">    return</span><span style="color:#ECEBE8"> { statusCode: </span><span style="color:#97CCAE">500</span><span style="color:#ECEBE8">, body: </span><span style="color:#EDCC95">err.toString</span><span style="color:#ECEBE8">() }</span></span>
<span class="line"><span style="color:#ECEBE8">  }</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span></code></pre></figure>
<p>Every function needs to export a handler, which in this case is an async function (convenient once we will need to asynchronously fetch data from Butter’s API). This function needs to return an object containing a <code>statusCode</code> indicating the HTTP Status of the request and a body with the payload. You can learn more about the <code>handler</code> method in the <a href="https://www.netlify.com/docs/functions/#the-handler-method" rel="noopener noreferrer" target="_blank">docs</a>.</p>
<p>The process of fetching data from Butter is pretty straightforward. Make sure you have it installed:</p>
<figure class="code"><figcaption>sh</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="sh"><code><span class="line"><span style="color:#EDCC95">npm</span><span style="color:#97CCAE"> install</span><span style="color:#97CCAE"> --save</span><span style="color:#97CCAE"> buttercms</span></span></code></pre></figure>
<p>And then setup Butter’s client pretty much how you would do with a regular React app:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">const</span><span style="color:#ECEBE8"> Butter </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> require</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'buttercms'</span><span style="color:#ECEBE8">);</span></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#ECEBE8"> API_KEY </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> “</span><span style="color:#A1C1E4">&#x3C;</span><span style="color:#ECEBE8">YOUR_API_KEY</span><span style="color:#A1C1E4">></span><span style="color:#ECEBE8">”;</span></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#ECEBE8"> butter </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> Butter</span><span style="color:#ECEBE8">(API_KEY);</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">exports</span><span style="color:#ECEBE8">.</span><span style="color:#EDCC95">handler</span><span style="color:#A1C1E4"> =</span><span style="color:#A1C1E4"> async</span><span style="color:#ECEBE8"> (event, context) </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  try</span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">    const</span><span style="color:#ECEBE8"> response </span><span style="color:#A1C1E4">=</span><span style="color:#A1C1E4"> await</span><span style="color:#EDCC95"> butter.post.list</span><span style="color:#ECEBE8">({page: </span><span style="color:#97CCAE">1</span><span style="color:#ECEBE8">, page_size: </span><span style="color:#97CCAE">10</span><span style="color:#ECEBE8">});</span></span>
<span class="line"><span style="color:#A1C1E4">    return</span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#ECEBE8">      statusCode: </span><span style="color:#97CCAE">200</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#ECEBE8">      body: </span><span style="color:#EDCC95">JSON.stringify</span><span style="color:#ECEBE8">({ data: response.data })</span></span>
<span class="line"><span style="color:#ECEBE8">    };</span></span>
<span class="line"><span style="color:#ECEBE8">  } </span><span style="color:#A1C1E4">catch</span><span style="color:#ECEBE8"> (err) {</span></span>
<span class="line"><span style="color:#A1C1E4">    return</span><span style="color:#ECEBE8"> { statusCode: </span><span style="color:#97CCAE">500</span><span style="color:#ECEBE8">, body: </span><span style="color:#EDCC95">err.toString</span><span style="color:#ECEBE8">() };</span></span>
<span class="line"><span style="color:#ECEBE8">  }</span></span>
<span class="line"><span style="color:#ECEBE8">};</span></span></code></pre></figure>
<p>Don’t forget to change <code>&#x3C;YOUR_API_KEY></code> to your personal key. Go again to <a href="http://localhost:8888/.netlify/functions/posts-by-month" rel="noopener noreferrer" target="_blank">http://localhost:8888/.netlify/functions/posts-by-month</a> and verify that it’s returning the correct data.</p>
<h3 id="grouping-by-month">Grouping by month</h3>
<p>The API is returning data, but that’s not exactly what we want. Ideally, we need to leverage the server processing power to make some computations for us. Let us grab only the published attribute of each post and map it to its corresponding month. The <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date" rel="noopener noreferrer" target="_blank">JavaScript Date object</a> allows us to do that by creating a <code>Date</code> instance and calling the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getMonth" rel="noopener noreferrer" target="_blank">getMonth</a> method. This method returns a number ranging from 0-11 which represents the months from January to December.</p>
<p>Our function should look like this:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">...</span></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#ECEBE8"> response </span><span style="color:#A1C1E4">=</span><span style="color:#A1C1E4"> await</span><span style="color:#EDCC95"> butter.post.list</span><span style="color:#ECEBE8">({page: </span><span style="color:#97CCAE">1</span><span style="color:#ECEBE8">, page_size: </span><span style="color:#97CCAE">10</span><span style="color:#ECEBE8">});</span></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#ECEBE8"> postsByMonth </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> {};</span></span>
<span class="line"><span style="color:#ECEBE8">response.data.data</span></span>
<span class="line"><span style="color:#EDCC95">  .map</span><span style="color:#ECEBE8">(post </span><span style="color:#A1C1E4">=></span><span style="color:#A1C1E4"> new</span><span style="color:#EDCC95"> Date</span><span style="color:#ECEBE8">(post.published)</span><span style="color:#EDCC95">.getMonth</span><span style="color:#ECEBE8">())</span></span>
<span class="line"><span style="color:#EDCC95">  .forEach</span><span style="color:#ECEBE8">(monthIndex </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">    if</span><span style="color:#ECEBE8"> ( postsByMonth[monthIndex] ) postsByMonth[monthIndex]</span><span style="color:#A1C1E4">++</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#A1C1E4">    else</span><span style="color:#ECEBE8"> postsByMonth[monthIndex] </span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE"> 1</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#ECEBE8">  });</span></span>
<span class="line"><span style="color:#A1C1E4">return</span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#ECEBE8">  statusCode: </span><span style="color:#97CCAE">200</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#ECEBE8">  body: </span><span style="color:#EDCC95">JSON.stringify</span><span style="color:#ECEBE8">(postsByMonth)</span></span>
<span class="line"><span style="color:#ECEBE8">};</span></span></code></pre></figure>
<p>Basically, we create a <code>postsByMonth</code> object which will hold the total number of posts retrieved by the API for every month that has any record. So if we had 2 posts in April, <code>postsByMonth[3]</code> will return <code>2</code>. If none were written in March, <code>postsByMonth[2]</code> will be <code>undefined</code>.</p>
<p>Our API is already achieving our simple requirements, but let’s improve it a bit.</p>
<h3 id="limiting-the-number-of-returned-posts">Limiting the number of returned posts</h3>
<p>In the hello world example we paid little attention to this line:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">const</span><span style="color:#ECEBE8"> subject </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> event.queryStringParameters.name </span><span style="color:#A1C1E4">||</span><span style="color:#97CCAE"> 'World'</span></span></code></pre></figure>
<p>We can resort to a similar technique to allow the user to set the limit for the query.</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">...</span></span>
<span class="line"><span style="color:#A1C1E4">exports</span><span style="color:#ECEBE8">.</span><span style="color:#EDCC95">handler</span><span style="color:#A1C1E4"> =</span><span style="color:#A1C1E4"> async</span><span style="color:#ECEBE8"> (event, context) </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  try</span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">    const</span><span style="color:#ECEBE8"> limit </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> event.queryStringParameters.limit </span><span style="color:#A1C1E4">||</span><span style="color:#97CCAE"> 10</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#A1C1E4">    const</span><span style="color:#ECEBE8"> response </span><span style="color:#A1C1E4">=</span><span style="color:#A1C1E4"> await</span><span style="color:#EDCC95"> butter.post.list</span><span style="color:#ECEBE8">({page: </span><span style="color:#97CCAE">1</span><span style="color:#ECEBE8">, page_size: limit});</span></span>
<span class="line"><span style="color:#A1C1E4">    ...</span></span>
<span class="line"><span style="color:#ECEBE8">  };</span></span></code></pre></figure>
<p>That’s not the only way to pass data to our Lambda function. The body of the request can be accessed via:</p>
<figure class="code"><figcaption>js</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="js"><code><span class="line"><span style="color:#A1C1E4">const</span><span style="color:#ECEBE8"> body </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> JSON.parse</span><span style="color:#ECEBE8">(event.body)</span></span></code></pre></figure>
<h3 id="adding-an-environment-variable">Adding an environment variable</h3>
<p>Currently, we are hardcoding the API key in the code. This is less problematic than having it in the client, but it’s still suboptimal (you might forget and commit its value to Git, for example). One of the nicest features of Netlify Dev is that it automatically injects all env variables that you have set on Netlify in your local server.</p>
<p>Open your site’s dashboard on Netlify and head to <em>Settings > Build &#x26; Deploy > Environment</em>. There, click on <em>Edit Variables</em> and add <code>BUTTER_API_KEY</code> as “Key” and your API key as “Value”.</p>
<figure class="image"><img alt="Netlify environment panel" loading="lazy" decoding="async" width="974" height="331" src="https://rafaelquintanilha.com/_astro/netlify-env-panel.DlXD3Lm5_Z1qJUTB.webp"><figcaption>Netlify environment panel</figcaption></figure>
<p>Next, initialize Butter making sure you read the API key from the env context:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">const</span><span style="color:#ECEBE8"> Butter </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> require</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'buttercms'</span><span style="color:#ECEBE8">);</span></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#ECEBE8"> API_KEY </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> process.env.BUTTER_API_KEY;</span></span>
<span class="line"><span style="color:#A1C1E4">...</span></span></code></pre></figure>
<p>Restart the dev server and check that it works!</p>
<h3 id="calling-the-api">Calling the API</h3>
<p>So far we have been testing our API directly in the browser. In order to exemplify how to consume this data in a real application, let us write a simple front-end that will make the request.</p>
<p>Delete everything in <code>src/App.js</code> and replace with:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> React </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'react'</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">function</span><span style="color:#EDCC95"> App</span><span style="color:#ECEBE8">() {</span></span>
<span class="line"><span style="color:#A1C1E4">  return</span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">button</span><span style="color:#ECEBE8">>Fetch API&#x3C;/</span><span style="color:#A1C1E4">button</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">  )</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">export</span><span style="color:#A1C1E4"> default</span><span style="color:#ECEBE8"> App</span></span></code></pre></figure>
<p>Next, install <a href="https://www.npmjs.com/package/isomorphic-fetch" rel="noopener noreferrer" target="_blank">isomorphic-fetch</a>:</p>
<figure class="code"><figcaption>sh</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="sh"><code><span class="line"><span style="color:#EDCC95">npm</span><span style="color:#97CCAE"> install</span><span style="color:#97CCAE"> --save</span><span style="color:#97CCAE"> isomorphic-fetch</span></span></code></pre></figure>
<p>We want to fetch data upon click and then render a table with the count for every month. If a month is not present, it means there were no posts. The full code is as follows:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> React, { useState } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'react'</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> fetch </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'isomorphic-fetch'</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> indexToMonth</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> index </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  switch</span><span style="color:#ECEBE8"> (index) {</span></span>
<span class="line"><span style="color:#A1C1E4">    case</span><span style="color:#97CCAE"> 0</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#A1C1E4">      return</span><span style="color:#97CCAE"> 'Jan'</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">    // Omitted for brevity</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">    case</span><span style="color:#97CCAE"> 11</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#A1C1E4">      return</span><span style="color:#97CCAE"> 'Dec'</span></span>
<span class="line"><span style="color:#A1C1E4">    default</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#A1C1E4">      return</span><span style="color:#97CCAE"> ''</span></span>
<span class="line"><span style="color:#ECEBE8">  }</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">function</span><span style="color:#EDCC95"> App</span><span style="color:#ECEBE8">() {</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> [postsByMonth, setPostsByMonth] </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> useState</span><span style="color:#ECEBE8">(</span><span style="color:#A1C1E4">null</span><span style="color:#ECEBE8">)</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#EDCC95"> onClick</span><span style="color:#A1C1E4"> =</span><span style="color:#A1C1E4"> async</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">    try</span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">      const</span><span style="color:#ECEBE8"> response </span><span style="color:#A1C1E4">=</span><span style="color:#A1C1E4"> await</span><span style="color:#EDCC95"> fetch</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'/.netlify/functions/posts-by-month'</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#A1C1E4">      const</span><span style="color:#ECEBE8"> json </span><span style="color:#A1C1E4">=</span><span style="color:#A1C1E4"> await</span><span style="color:#EDCC95"> response.json</span><span style="color:#ECEBE8">()</span></span>
<span class="line"><span style="color:#EDCC95">      setPostsByMonth</span><span style="color:#ECEBE8">(json)</span></span>
<span class="line"><span style="color:#ECEBE8">    } </span><span style="color:#A1C1E4">catch</span><span style="color:#ECEBE8"> (e) {</span></span>
<span class="line"><span style="color:#EDCC95">      console.error</span><span style="color:#ECEBE8">(e)</span></span>
<span class="line"><span style="color:#ECEBE8">    }</span></span>
<span class="line"><span style="color:#ECEBE8">  }</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">  return</span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">button</span><span style="color:#EDCC95"> onClick</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{onClick}>Fetch API&#x3C;/</span><span style="color:#A1C1E4">button</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      {postsByMonth </span><span style="color:#A1C1E4">&#x26;&#x26;</span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;</span><span style="color:#A1C1E4">table</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">          &#x3C;</span><span style="color:#A1C1E4">thead</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">            &#x3C;</span><span style="color:#A1C1E4">tr</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">              &#x3C;</span><span style="color:#A1C1E4">th</span><span style="color:#ECEBE8">>Month&#x3C;/</span><span style="color:#A1C1E4">th</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">              &#x3C;</span><span style="color:#A1C1E4">th</span><span style="color:#ECEBE8">>Posts&#x3C;/</span><span style="color:#A1C1E4">th</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">            &#x3C;/</span><span style="color:#A1C1E4">tr</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">          &#x3C;/</span><span style="color:#A1C1E4">thead</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">          &#x3C;</span><span style="color:#A1C1E4">tbody</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">            {</span><span style="color:#EDCC95">Array</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">12</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#EDCC95">              .fill</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">0</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#EDCC95">              .map</span><span style="color:#ECEBE8">((el, i) </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">                &#x3C;</span><span style="color:#A1C1E4">tr</span><span style="color:#EDCC95"> key</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{i}></span></span>
<span class="line"><span style="color:#ECEBE8">                  &#x3C;</span><span style="color:#A1C1E4">td</span><span style="color:#ECEBE8">>{</span><span style="color:#EDCC95">indexToMonth</span><span style="color:#ECEBE8">(i)}&#x3C;/</span><span style="color:#A1C1E4">td</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">                  &#x3C;</span><span style="color:#A1C1E4">td</span><span style="color:#ECEBE8">>{postsByMonth[i] </span><span style="color:#A1C1E4">||</span><span style="color:#97CCAE"> 0</span><span style="color:#ECEBE8">}&#x3C;/</span><span style="color:#A1C1E4">td</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">                &#x3C;/</span><span style="color:#A1C1E4">tr</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">              ))}</span></span>
<span class="line"><span style="color:#ECEBE8">          &#x3C;/</span><span style="color:#A1C1E4">tbody</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;/</span><span style="color:#A1C1E4">table</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      )}</span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">  )</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">export</span><span style="color:#A1C1E4"> default</span><span style="color:#ECEBE8"> App</span></span></code></pre></figure>
<p>All we do is to fetch data from our serverless API and save it with <code>useState</code>. If you are unfamiliar with React Hooks, check this <a href="https://rafaelquintanilha.com/how-to-reuse-logic-with-react-hooks">comprehensive article</a> which will guide you through what is essential.</p>
<p>Then, we iterate over an array of size 12 (using ES6 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill" rel="noopener noreferrer" target="_blank">Array.fill</a> method) and render the correct value for each month. For brevity, I omitted the full extent of <code>indexToMonth</code>, but it should be pretty clear.</p>
<p>Go to <a href="http://localhost:8888/" rel="noopener noreferrer" target="_blank">http://localhost:8888/</a> and check your serverless-powered app!</p>
<figure class="image"><img alt="Fetching data from serverless API" loading="lazy" decoding="async" width="265" height="333" src="https://rafaelquintanilha.com/_astro/fetch.BQE_WQgB_Z1R85bh.webp"><figcaption>Fetching data from serverless API</figcaption></figure>
<h2 id="final-thoughts">Final thoughts</h2>
<p>Serverless goes way beyond the current hype. It definitely removes development overhead and therefore has inherent value. In the book <em>Antifragile</em>, the author Nassim Nicholas Taleb warns us against “overhyping” and “neomania”. According to him:</p>
<blockquote>
<p>“People acquire a new item, feel more satisfied after an initial boost, then rapidly revert to their baseline of well-being. So when you “upgrade”, you feel a boost of satisfaction with changes in technology. But then you get used to it and start hunting for the new new thing.”</p>
</blockquote>
<p>We can apply the same principle to software development. Yet, things <em>do</em> evolve and <em>do</em> get better. How can you tell what’s worthy from what’s purely <em>neomania</em>?</p>
<p>Taleb exemplifies with wall-to-wall windows. With today’s technology, we can avoid heavy and thick windows that helped our predecessors’ homes stay warm. That approaches humans to nature. In other words, when technology is used to <em>remove</em> a constraint imposed by <em>technology itself</em> in the past.</p>
<p>How can we relate that principle with what we learned today? Serverless connects us with what is really important (developing a great product) by removing the infrastructure burden that was important in the past but can be dispensable in some cases.</p>
<p>Anyway, we have seen that serverless is not a silver bullet. In particular, it might not suit your needs if you need more control over your server.</p>
<p>Finally, combine Netlify with ButterCMS to avoid expensive computations in your clients’ browsers, improve security and enhance the API to fit your requirements.</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[How to Reuse Logic with React Hooks]]></title>
<description><![CDATA[Learn why Hooks are a game-changer and write your first hook.]]></description>
<link>https://rafaelquintanilha.com/how-to-reuse-logic-with-react-hooks/</link>
<guid isPermaLink="false">6370534742a473003d9dca83</guid>
<category><![CDATA[React]]></category><category><![CDATA[ButterCMS]]></category>
<dc:creator><![CDATA[Rafael Quintanilha]]></dc:creator>
<pubDate>Tue, 25 Jun 2019 03:00:00 GMT</pubDate>

<content:encoded><![CDATA[<p>React has always been great for reusing and composing <em>components</em>. That means you can write a piece of UI and simply reuse it later on. Moreover, your component can have some embedded logic that you can reuse too. Write once, and use everywhere. A big win!</p>
<p>But what if you want to reuse the logic <em>only</em>? It means that you don’t care about the UI, but you care about the behavior of the component. Can you still write it once and use it everywhere?</p>
<p>And the answer is… yes! React developers have designed all kinds of patterns for reusing logic, the most prominent being <em>Higher-Order Components (HOC)</em> and <em>Render Props</em>. They work and have been in use for quite a while. But still, those two approaches don’t feel quite right and have some shortcomings (which we will see soon). What could be a possible alternative?</p>
<p><a href="https://reactjs.org/blog/2019/02/06/react-v16.8.0.html" rel="noopener noreferrer" target="_blank">As of React 16.8, Hooks were introduced</a>. Hooks are a way to reuse <em>logic</em> across applications. You write a specific behavior (logic) and “hook” it into any component. This component now can use this logic normally.</p>
<h3 id="why-do-we-need-react-hooks">Why do we need React Hooks?</h3>
<p>Consider that you want to add a clock into your application. Clearly, you think, this is something very common that someone might have already developed. You find a React library that renders the clock and exposes a few props to customize its style and functionality (size, display seconds or not, frequency of update, etc). After a few tweaks, you have your component pretty similar to what you want, though <em>not quite</em>. Maybe you want to customize only the hours (make it bigger) or add a different color to the minutes. In the end, you wish you could just use the clock <em>logic</em> and style it exactly how you want.</p>
<p>This scenario is a great use case for Hooks. You can “hook” the “clock behavior” into a component and have the current time available. Then, you just use the time as you would use any variable declared in the scope of your component, the difference being that you don’t need to worry about it (in case you are curious, check the <a href="https://github.com/rafaelquintanilha/use-clock" rel="noopener noreferrer" target="_blank">useClock</a> hook that I developed and that illustrates this principle).</p>
<p>But before diving deeper into Hooks, let us understand the issues with the former solutions.</p>
<h1 id="the-world-before-hooks">The world before Hooks</h1>
<p>We have seen that React is great for reusing UI but that sometimes we might be interested only in the logic behind a component. Hooks are an answer to this demand. Let’s examine how we reused logic in the <em>pre</em>-Hooks era.</p>
<h3 id="higher-order-components-hoc">Higher-Order Components (HOC)</h3>
<p>Probably the first pattern to be widely adopted by the React community on this matter, HOCs, solved the reusable logic problem using <em>composition</em>. Here is the idea: you develop a component that implements the logic and passes the computed values (for example, the current time) to the children, which have access to the values via props. Generically:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#ECEBE8">&#x3C;</span><span style="color:#A1C1E4">ComponentWhichImplementsLogic</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">  &#x3C;</span><span style="color:#A1C1E4">ComponentWhichUsesLogic</span><span style="color:#ECEBE8"> /></span></span>
<span class="line"><span style="color:#ECEBE8">&#x3C;</span><span style="color:#A1C1E4">ComponentWhichImplementsLogic</span><span style="color:#ECEBE8">></span></span></code></pre></figure>
<p>Because <code>&#x3C;ComponentWhichImplementsLogic></code> is higher in the DOM order, we call them <em>Higher-Order Components</em>. HOCs conventionally start with the <em>with</em> prefix.</p>
<p>We can make them more legible by creating a function that accepts a component and returns this component with the injected logic:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#EDCC95">ComponentWhichImplementsLogic</span><span style="color:#ECEBE8">(ComponentWhichUsesLogic)</span></span></code></pre></figure>
<p>Or, recalling our example:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#EDCC95">withClock</span><span style="color:#ECEBE8">(MyComponent)</span></span></code></pre></figure>
<p>Considering that <code>withClock</code> is an HOC which implements the clock feature and exposes the current time, <code>MyComponent</code> would then access the current time via props. I won’t dive into the specifics of the development, but consider that a <code>withClock</code> component would store the current time in the state, add a <code>setInterval</code> in <code>componentDidMount</code> that increments the time at each interval, and does the proper cleanup when unmounted (calls <code>clearInterval</code>).</p>
<p>The first problem with this approach is that using multiple HOCs starts to become cumbersome. Suppose you also want your component to track the user’s current mouse position:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#EDCC95">withMousePosition</span><span style="color:#ECEBE8">(</span><span style="color:#EDCC95">withClock</span><span style="color:#ECEBE8">(MyComponent))</span></span></code></pre></figure>
<p>And you can certainly imagine why this is suboptimal if the number of injected logic grows. Also, it makes debugging and testing a pain. If your component misbehaves, detecting the flaw in a tree of HOCs won’t be pleasant.</p>
<h3 id="render-props">Render Props</h3>
<p>When people started complaining about the issues of Higher-Order Components, a new pattern emerged: <em>render props.</em> You can read all about it <a href="https://cdb.reacttraining.com/use-a-render-prop-50de598f11ce" rel="noopener noreferrer" target="_blank">in this very popular post by Michael Jackson</a>. Basically, the component which implements the logic receives a <em>render prop</em> and calls it in its <em>own</em> render function, but now exposing the computed values:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#ECEBE8">&#x3C;</span><span style="color:#A1C1E4">Clock</span><span style="color:#EDCC95"> render</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{props </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> &#x3C;</span><span style="color:#A1C1E4">MyComponent</span><span style="color:#ECEBE8"> {</span><span style="color:#A1C1E4">...</span><span style="color:#ECEBE8">props} />} /></span></span></code></pre></figure>
<p>This way, whatever props are returned by <code>Clock</code>, will be accessible to <code>MyComponent</code>. The render props pattern avoids some hard to debug issues such as name collision (suppose you accidentally override a prop or state name) and is somewhat less verbose, despite the excess of JSX.</p>
<p>While the community seemed to adopt the render props pattern, composing logic is still suboptimal and some started to complain about the dreaded <a href="https://twitter.com/acdlite/status/955954032194895872?ref_src=twsrc%5Etfw%7Ctwcamp%5Etweetembed%7Ctwterm%5E955954032194895872&#x26;ref_url=https%3A%2F%2Fwww.richardkotze.com%2Fcoding%2Fhoc-vs-render-props-react" rel="noopener noreferrer" target="_blank">callback hell</a>:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#ECEBE8">&#x3C;</span><span style="color:#A1C1E4">Clock</span><span style="color:#EDCC95"> render</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{({time}) </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">  &#x3C;</span><span style="color:#A1C1E4">Mouse</span><span style="color:#EDCC95"> render</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{({x, y}) </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> ( </span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;</span><span style="color:#A1C1E4">MyComponent</span><span style="color:#EDCC95"> time</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{time} </span><span style="color:#EDCC95">x</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{x} </span><span style="color:#EDCC95">y</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{y} /></span></span>
<span class="line"><span style="color:#ECEBE8">  )} /></span></span>
<span class="line"><span style="color:#ECEBE8">)} /></span></span></code></pre></figure>
<p>This becomes unreadable pretty quickly. Clearly, there is still much room for improvement. Next, we will see what a Hooks approach would look like.</p>
<h1 id="the-hooks-solution">The Hooks solution</h1>
<p>While React definitely has alternatives for the reuse of <em>logic</em>, we have seen that it is suboptimal – particularly for composition (multiple logic being added to a single component can become too verbose, too hard to debug and too similar to callback hell).</p>
<p>Without further ado, consider how the former example could be written using hooks:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> MyComponent</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> [time] </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> useClock</span><span style="color:#ECEBE8">();</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> [x, y] </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> useMouseMove</span><span style="color:#ECEBE8">();</span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">  // do something with those values</span></span>
<span class="line"><span style="color:#A1C1E4">  return</span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">>Current time: {time}&#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">>Mouse coordinates: {x},{y}&#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;/></span></span>
<span class="line"><span style="color:#ECEBE8">  );</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span></code></pre></figure>
<p>That’s it! You simply declare your Hooks (in this case, <code>useClock</code> and <code>useMouseMove</code>) and have them instantly available inside your component. There is no extra work. Just plug it (hook) into your component and you are good to go.</p>
<p>Notice that we can use as many Hooks as we want. It is seamlessly composable and trivial to test (forget about a deep tree of nested components and weird inline JSX). And there is more: as you can see in the above example, <em>it works with functional components</em>, which reduces the verbosity of your component considerably (forget about using this or setting up constructors).</p>
<p>Indeed, with the advent of Hooks using class components are somewhat discouraged. <a href="https://reactjs.org/docs/hooks-faq.html#do-hooks-cover-all-use-cases-for-classes" rel="noopener noreferrer" target="_blank">According to the docs</a>, there are just a few edge cases where classes have no Hooks equivalent, so it is very likely that you can start using Hooks right away.</p>
<p>Does that mean that you need to rewrite all your class components using Hooks? <strong>Definitely not</strong>. Hooks are a powerful solution and it is being well received by the community. However, by no means feel like you should do a major rewrite just because of that.</p>
<p>With that being said, let’s understand the main differences between classes and Hooks.</p>
<h3 id="the-mental-model">The Mental Model</h3>
<p>One of the biggest distinctions between classes and Hooks is that <em>Hooks have no lifecycles</em>. For experienced React developers, this can take some time to click. We are used to thinking in terms of <code>componentDidMount</code>, <code>componentWillUpdate</code>, etc. But with Hooks things don’t work this way.</p>
<p>So the first thing you need to avoid is trying to map a given lifecycle to a particular use case with Hooks. This will only confuse you. Instead, just think that for Hooks any state or prop change calls the function again (recall your component is a function) with the updated values (state and props). For peace of mind, <a href="https://reactjs.org/docs/hooks-faq.html#how-do-lifecycle-methods-correspond-to-hooks" rel="noopener noreferrer" target="_blank">the docs give you a rough equivalency</a> of certain lifecycles in the Hooks world.</p>
<figure class="embed embed-twitter" data-url="https://twitter.com/webquintanilha/status/1140811628398743553">
<blockquote class="twitter-tweet"><p lang="en" dir="ltr">"[...] Hooks have no lifecycles. For experienced React developers, this can take some time to click. We are used to thinking in terms of componentDidMount, componentWillUpdate, etc. But with Hooks things don’t work this way."<br><br>My article on learning <a href="https://twitter.com/reactjs" rel="noopener noreferrer" target="_blank">@reactjs</a> Hooks 👇 <a href="https://t.co/8o6tUHkuDE" rel="noopener noreferrer" target="_blank">https://t.co/8o6tUHkuDE</a></p>— Rafael Quintanilha (@webquintanilha) <a href="https://twitter.com/webquintanilha/status/1140811628398743553" rel="noopener noreferrer" target="_blank">June 18, 2019</a></blockquote>
</figure>
<p>One of the core contributors to React, Dan Abramov, wrote in his blog <a href="https://overreacted.io/how-are-function-components-different-from-classes/" rel="noopener noreferrer" target="_blank">a piece on the differences between function and class components</a>. Go check it out if you are curious about the internals.</p>
<p>Now that we understand that Hooks do not operate based on lifecycles (like classes do), let’s examine how the most common Hooks work.</p>
<h3 id="usestate">useState</h3>
<p>The first and simplest Hook is <code>useState</code>. Basically, it does exactly what you would expect: you declare a variable and a setter. Here’s how it looks:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> React, { useState } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'react'</span><span style="color:#ECEBE8">;</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> Counter</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> [count, setCount] </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> useState</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">0</span><span style="color:#ECEBE8">);</span></span>
<span class="line"><span style="color:#A1C1E4">  return</span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">>Current count: {count}&#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">button</span><span style="color:#EDCC95"> onClick</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{() </span><span style="color:#A1C1E4">=></span><span style="color:#EDCC95"> setCount</span><span style="color:#ECEBE8">(count </span><span style="color:#A1C1E4">+</span><span style="color:#97CCAE"> 1</span><span style="color:#ECEBE8">)}>Increment&#x3C;/</span><span style="color:#A1C1E4">button</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">  );</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span></code></pre></figure>
<p>As you can see, the hook returns an array with two elements and takes one parameter.</p>
<ul>
<li>The first element of the array is the current value for this state;</li>
<li>The second element of the array is a setter that changes the value of this state;</li>
<li>The parameter used in the hook (in our example, 0) is the initial value of this state.</li>
</ul>
<p>Naturally, you can add multiple states by adding multiple hooks:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> Counter</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> [count, setCount] </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> useState</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">0</span><span style="color:#ECEBE8">);</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> [step, setStep] </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> useState</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">1</span><span style="color:#ECEBE8">);</span></span>
<span class="line"><span style="color:#A1C1E4">  return</span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">>Current count: {count}&#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">button</span><span style="color:#ECEBE8"> </span></span>
<span class="line"><span style="color:#EDCC95">        onClick</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{() </span><span style="color:#A1C1E4">=></span><span style="color:#EDCC95"> setCount</span><span style="color:#ECEBE8">(count </span><span style="color:#A1C1E4">+</span><span style="color:#ECEBE8"> step)}></span></span>
<span class="line"><span style="color:#ECEBE8">        Increment by {step}</span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;/</span><span style="color:#A1C1E4">button</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">  );</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span></code></pre></figure>
<p>Now recall that with Hooks every re-render is nothing else than the function being called again (in our example, <code>Counter</code>). But for every re-render, the state will be updated with its current value. This is the main difference between a state variable and a regular variable. Regular variables will always be re-defined.  State variables will be derived from the previous state.</p>
<p>How do we trigger a re-render? Every time a prop or state variable changes we trigger a re-render.  This is done by invoking the setter, in our example through the click of the button. This is important to know so we can better understand the next Hook.</p>
<h3 id="useref">useRef</h3>
<p>Sometimes we want to store a value in our component for future reference, but we don’t want to trigger a re-render (as this value isn’t expected to change often or has little or no UI impact). This would be the equivalent of having a class property:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">this</span><span style="color:#ECEBE8">.myValue </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> value;</span></span></code></pre></figure>
<p>To address this case, <code>useRef</code> was introduced. Refs give us a way to store a variable in the scope of the function and preserve its value across renders. One typical case is to set a reference into an HTML component:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> React, { useRef } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'react'</span><span style="color:#ECEBE8">;</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> FocusInput</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> inputRef </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> useRef</span><span style="color:#ECEBE8">(</span><span style="color:#A1C1E4">null</span><span style="color:#ECEBE8">);</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#EDCC95"> onClick</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#EDCC95"> inputRef.current.focus</span><span style="color:#ECEBE8">();</span></span>
<span class="line"><span style="color:#A1C1E4">  return</span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">input</span><span style="color:#EDCC95"> ref</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{inputRef} /></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">button</span><span style="color:#EDCC95"> onClick</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{onClick}>Focus&#x3C;/</span><span style="color:#A1C1E4">button</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">  );</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span></code></pre></figure>
<p>Notice that <code>useRef</code> receives an initial value (in our example, <code>null</code>) and returns the ref variable. Whatever is stored in this ref can be accessed via <code>myRef.current</code>, so when we assign the ref of the input element to <code>inputRef</code>, <code>inputRef.current</code> holds the actual DOM element, allowing us to programmatically trigger focus.</p>
<p>In fact, <code>useRef</code> is a special case of <code>useState</code>, but one that we set its value directly instead of using a setter, which persists the value across renders without triggering a re-render.</p>
<figure class="embed embed-twitter" data-url="https://twitter.com/webquintanilha/status/1138915113824595968">
<blockquote class="twitter-tweet"><p lang="en" dir="ltr">useRef vs useState<br><br>What's the difference between the two Hooks?<br><br>useRef is a special case of useState: <a href="https://t.co/Y2tCnuBeQZ" rel="noopener noreferrer" target="_blank">https://t.co/Y2tCnuBeQZ</a><br><br>- useRef persists values across re-renders<br>- changing useRef does not trigger a re-render<br><br>More about <a href="https://twitter.com/hashtag/hooks?src=hash&#x26;ref_src=twsrc%5Etfw" rel="noopener noreferrer" target="_blank">#hooks</a>: <a href="https://t.co/7MRBkpAHXL" rel="noopener noreferrer" target="_blank">https://t.co/7MRBkpAHXL</a></p>— Rafael Quintanilha (@webquintanilha) <a href="https://twitter.com/webquintanilha/status/1138915113824595968" rel="noopener noreferrer" target="_blank">June 12, 2019</a></blockquote>
</figure>
<p>If you want to learn refs in depth, <a href="https://rafaelquintanilha.com/the-complete-guide-to-react-refs/">The Complete Guide to React Refs</a> has a comprehensive coverage of how refs work.</p>
<p>So far we have learned how to manipulate variables inside a component using Hooks. We are still missing how to respond to some events. For example, how can I fetch data from an API when the component mounts, or how can I perform an operation if a particular state changed?</p>
<h3 id="useeffect">useEffect</h3>
<p>The <code>useEffect</code> hook can be tricky to grasp, particularly if you think too much in terms of old React class lifecycles. It has some subtleties that are not immediate but definitely make sense. Let us start from the beginning: what exactly is an effect?</p>
<blockquote>
<p>An <em>effect</em>, or <em>side effect</em>, is an operation that you run after a render.</p>
</blockquote>
<p>A practical example: suppose you have a component that fetches a list of products for a given category. Once your component renders (“mounts”) you want to trigger the API call. And if later the category changes (for example if the user navigates from the sports section to the fashion section of an e-commerce site), you want to call the API again.</p>
<p>Notice that with what we learned about <code>useState</code> and <code>useRef</code> we are unable to do so. We currently haven’t learned a way to only perform operations given that certain things happened to our state or props.</p>
<p>In the old-style class component, our example would look like this:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">class</span><span style="color:#EDCC95"> ProductsList</span><span style="color:#A1C1E4"> extends</span><span style="color:#EDCC95"> React</span><span style="color:#ECEBE8">.Component {</span></span>
<span class="line"><span style="color:#EDCC95">  componentDidMount</span><span style="color:#ECEBE8">() {</span></span>
<span class="line"><span style="color:#A1C1E4">    this</span><span style="color:#EDCC95">.getProducts</span><span style="color:#ECEBE8">()</span></span>
<span class="line"><span style="color:#ECEBE8">  }</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">  componentDidUpdate</span><span style="color:#ECEBE8">(prevProps) {</span></span>
<span class="line"><span style="color:#A1C1E4">    if</span><span style="color:#ECEBE8"> ( prevProps.categoryId </span><span style="color:#A1C1E4">!==</span><span style="color:#A1C1E4"> this</span><span style="color:#ECEBE8">.props.categoryId ) {</span></span>
<span class="line"><span style="color:#A1C1E4">      this</span><span style="color:#EDCC95">.getProducts</span><span style="color:#ECEBE8">();</span></span>
<span class="line"><span style="color:#ECEBE8">    }</span></span>
<span class="line"><span style="color:#ECEBE8">  }</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">  getProducts</span><span style="color:#ECEBE8">() {</span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">    // perform API call with this.props.categoryId</span></span>
<span class="line"><span style="color:#ECEBE8">  }</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">  ...</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span></code></pre></figure>
<p>Now, what is the Hooks equivalent?</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> ProductsList</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> props </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#EDCC95"> getProducts</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">    // perform API call with props.categoryId</span></span>
<span class="line"><span style="color:#ECEBE8">  }</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">  useEffect</span><span style="color:#ECEBE8">(() </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#EDCC95">    getProducts</span><span style="color:#ECEBE8">();</span></span>
<span class="line"><span style="color:#ECEBE8">  });</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">  ...</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span></code></pre></figure>
<p>This looks way cleaner. We define an <em>effect</em> which accepts a function that will be called after render and then will perform some operation (here, call <code>getProducts</code>). However, this isn’t quite right yet. The above code runs the effect after every render. How can we fix that?</p>
<p>Luckily, <code>useEffect</code> accepts a dependency array. It means that you can declare upon which state or props change you want to trigger the effect. For us, it would look like this:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#EDCC95">useEffect</span><span style="color:#ECEBE8">(() </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#EDCC95">  getProducts</span><span style="color:#ECEBE8">();</span></span>
<span class="line"><span style="color:#ECEBE8">}, [props.categoryId]);</span></span></code></pre></figure>
<p>The above code will run after the first render and in all renders caused by a change in <code>props.categoryId</code>. It is a combination of <code>componentDidMount</code> and <code>componentDidUpdate</code>.</p>
<p>What if you want to call the effect only on “mount” (or in Hooks jargon, after the first render)?</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#EDCC95">useEffect</span><span style="color:#ECEBE8">(() </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#EDCC95">  getProducts</span><span style="color:#ECEBE8">();</span></span>
<span class="line"><span style="color:#ECEBE8">}, []);</span></span></code></pre></figure>
<p>The answer is to make the dependency array an empty one. Remember that when we add a dependency array, the effect gets called after the first render and whenever any of the values in the array change. Logically, if there is no element in the array, it will only be called after the first render.</p>
<p>If you want to run your effect after every render, simply remove the dependency array at all (like in our first example). However, make sure you know what you are doing because this can cause performance issues (imagine calling an API whenever a component with plenty of states and props re-renders).</p>
<p>There is one last thing that I want to mention about <code>useEffect</code>. Sometimes you might want to do a cleanup, the equivalent of the <code>componentWillUnmount</code> lifecycle. For example, you might have added a DOM listener that you want to remove upon unmount. Recall our <code>useMouseMove</code> hook? Here is how we can implement it with Hooks using what we have learned so far:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> React, { useState, useEffect } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'react'</span><span style="color:#ECEBE8">;</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> useMouseMove</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> [coords, setCoords] </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> useState</span><span style="color:#ECEBE8">([</span><span style="color:#97CCAE">0</span><span style="color:#ECEBE8">, </span><span style="color:#97CCAE">0</span><span style="color:#ECEBE8">]);</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">  useEffect</span><span style="color:#ECEBE8">(() </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">    const</span><span style="color:#EDCC95"> handler</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> ({ clientX, clientY }) </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#EDCC95">      setCoords</span><span style="color:#ECEBE8">([clientX, clientY]);</span></span>
<span class="line"><span style="color:#ECEBE8">    };</span></span>
<span class="line"><span style="color:#EDCC95">    window.addEventListener</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'mousemove'</span><span style="color:#ECEBE8">, handler);</span></span>
<span class="line"><span style="color:#A1C1E4">    return</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#EDCC95">      window.removeEventListener</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'mousemove'</span><span style="color:#ECEBE8">, handler);</span></span>
<span class="line"><span style="color:#ECEBE8">    };</span></span>
<span class="line"><span style="color:#ECEBE8">  }, []);</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">  return</span><span style="color:#ECEBE8"> coords;</span></span>
<span class="line"><span style="color:#ECEBE8">};</span></span></code></pre></figure>
<p><a href="https://github.com/donavon/use-event-listener" rel="noopener noreferrer" target="_blank">The above is outlined in the terrific use-event-listener library</a>. After the first render, you add a listener to the window object and call a cleanup function when the component is removed from the DOM. Whatever function you return from inside your effect will be called upon unmount. <a href="https://reactjs.org/docs/hooks-effect.html#effects-with-cleanup" rel="noopener noreferrer" target="_blank">The official docs</a> provide more details if you want to dive deeper.</p>
<p>Finally, in the Overreact blog by Dan Abramov, <a href="https://overreacted.io/a-complete-guide-to-useeffect/" rel="noopener noreferrer" target="_blank">there is a comprehensive guide</a> of <code>useEffect</code>. The post is very long but I encourage you to find some time and read it if you want to master <code>useEffect</code>.</p>
<h3 id="other-hooks">Other Hooks</h3>
<p>There are several other built-in Hooks in the new API. All of them are described in the <a href="https://reactjs.org/docs/hooks-reference.html" rel="noopener noreferrer" target="_blank">API reference</a>, but I will highlight some:</p>
<h4 id="usecontext">useContext</h4>
<p>Equivalent to the <a href="https://reactjs.org/docs/context.html" rel="noopener noreferrer" target="_blank">Context API</a>. Allows your component to read from a Context:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">const</span><span style="color:#ECEBE8"> value </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> useContext</span><span style="color:#ECEBE8">(MyContext);</span></span></code></pre></figure>
<h4 id="usereducer">useReducer</h4>
<p>For some time, state management libraries such as Redux were a controversial point in the React community. They evolved over the years but the hype has been diminishing. Hooks, however, provide a very neat way to add a reducer to your component.</p>
<p>A <em>reducer</em> is basically a function that accepts a state and an action. Based on the action, it updates the state. This leads the developer to a better encapsulation of the state, while increasing the maintainability of the state as it grows. <a href="https://reactjs.org/docs/hooks-reference.html#usereducer" rel="noopener noreferrer" target="_blank">More about useReducer in the docs</a>.</p>
<h4 id="usecallback">useCallback</h4>
<p>The last built-in Hook that I want to mention is <code>useCallback</code>. Basically, <code>useCallback</code> receives a function and a dependency array and memoizes that function until any of its dependencies change. It is useful for optimizations and borrows the <code>shouldComponentUpdate</code> mindset.</p>
<p>Suppose you render a <code>Button</code> component:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> Component</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#EDCC95"> onClick</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#EDCC95"> console.log</span><span style="color:#ECEBE8">(“Clicked”);</span></span>
<span class="line"><span style="color:#A1C1E4">  return</span><span style="color:#ECEBE8"> &#x3C;</span><span style="color:#A1C1E4">Button</span><span style="color:#EDCC95"> onClick</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{onClick}>Click&#x3C;/</span><span style="color:#A1C1E4">Button</span><span style="color:#ECEBE8">>;</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span></code></pre></figure>
<p>Whenever <code>Component</code> re-renders, <code>onClick</code> will be redefined (recall that we call the function scope every render). Once <code>onClick</code> essentially changed, <code>Button</code> will re-render too. But notice that <code>onClick</code> is in practice the same function, so we re-rendered <code>Button</code> unnecessarily!</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> Component</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> onClick </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> useCallback</span><span style="color:#ECEBE8">(() </span><span style="color:#A1C1E4">=></span><span style="color:#EDCC95"> console.log</span><span style="color:#ECEBE8">(“Clicked”), []);</span></span>
<span class="line"><span style="color:#A1C1E4">  return</span><span style="color:#ECEBE8"> &#x3C;</span><span style="color:#A1C1E4">Button</span><span style="color:#EDCC95"> onClick</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{onClick}>Click&#x3C;/</span><span style="color:#A1C1E4">Button</span><span style="color:#ECEBE8">>;</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span></code></pre></figure>
<p>The above code fixes our problem. By wrapping our function in <code>useCallback</code> we now have it memoized and only recreated if any value in the dependency array changes (in our case, because <code>useCallback</code> has no dependencies, it will never change).</p>
<p><code>useCallback</code> is very related to <code>useMemo</code>, which does basically the same thing, but memoizing the <em>result</em> of a function, not the function itself. There is a nice piece about their differences in this <a href="https://stackoverflow.com/a/54963730/4487722" rel="noopener noreferrer" target="_blank">Stack Overflow comment</a>.</p>
<h4 id="next">Next</h4>
<p>We have covered everything we needed (much more, in fact) to write our first hook. So the next section will stop the theory and explain how we can create a custom hook for ourselves.</p>
<h1 id="writing-your-first-hook">Writing your first hook</h1>
<p>So far we learned how to use Hooks to achieve the same things we would achieve with a class component. But recall that the greater goal of Hooks is to make logic <em>shareable</em>, so this is our next objective.</p>
<p>We saw a sneak peek of this process in the <code>useMouseMove</code> hook provided in the last section. Basically, we wrote a function that used some hooks (<code>useState</code> and <code>useEffect</code>) and returned a value.</p>
<p>For this section, we will write a <code>useButter</code> hook. This hook will make our life easier when injecting ButterCMS data in any component. <a href="https://buttercms.com/api-first-cms/" rel="noopener noreferrer" target="_blank">ButterCMS is a headless Content Management System that you can learn more about here</a>. Let’s get started writing our <code>useButter</code> hook.</p>
<h3 id="modeling-the-api">Modeling the API</h3>
<p><a href="http://buttercms.com/docs/api-client/react#Quickstart" rel="noopener noreferrer" target="_blank">Butter docs</a> cover all you need to know about using Butter in a React application. In short, once you have your Butter client set with the correct API key, listing the first 10 posts of your blog is as easy as:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#EDCC95">butter.post.list</span><span style="color:#ECEBE8">({page: </span><span style="color:#97CCAE">1</span><span style="color:#ECEBE8">, page_size: </span><span style="color:#97CCAE">10</span><span style="color:#ECEBE8">})</span><span style="color:#EDCC95">.then</span><span style="color:#ECEBE8">(</span><span style="color:#A1C1E4">function</span><span style="color:#ECEBE8">(response) {</span></span>
<span class="line"><span style="color:#EDCC95">  console.log</span><span style="color:#ECEBE8">(response);</span></span>
<span class="line"><span style="color:#ECEBE8">});</span></span></code></pre></figure>
<p>Notice that the butter client exposes us to some entities (in this example, <em>page</em>) and a few methods (in this example, <em>list</em>). Finally, we can also pass some options (in this example, the number of pages and the page size) and after the API resolves, access the response. <a href="https://buttercms.com/docs/api/?javascript#introduction" rel="noopener noreferrer" target="_blank">Check the API reference</a> for a complete list of entities and methods.</p>
<p>Ideally, our hook would receive the entity, method, and options, and return the API response. To give us more control over the network request, we will also need to know if the API is still loading or if it failed.</p>
<h3 id="creating-the-hook">Creating the Hook</h3>
<p>Let us now start creating our hook. All code in this article is present in <a href="https://github.com/rafaelquintanilha/butter-hooks-example" rel="noopener noreferrer" target="_blank">this GitHub repo</a>. Afterward, we will build a simple app that fetches posts from the ButterCMS API. <a href="https://butter-hooks-example.netlify.com/" rel="noopener noreferrer" target="_blank">Here’s a live preview</a>.</p>
<h4 id="setting-up-butter">Setting up Butter</h4>
<p>First, we will set up Butter and create the hook. When it’s done we then “hook” it into our component.</p>
<p>Go ahead and create your app. For the sake of this example, I’ll use <a href="https://facebook.github.io/create-react-app/" rel="noopener noreferrer" target="_blank">create-react-app</a>:</p>
<figure class="code"><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="plaintext"><code><span class="line"><span>npx create-react-app butter-hooks-example</span></span></code></pre></figure>
<p>Then, navigate to the newly created <em>butter-hooks-example</em> directory and add the butter library:</p>
<figure class="code"><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="plaintext"><code><span class="line"><span>yarn add buttercms</span></span></code></pre></figure>
<p>Once it’s done, create a file in the <em>src</em> folder called <em>butter-client.js</em> and add the following:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> Butter </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'buttercms'</span><span style="color:#ECEBE8">;</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#ECEBE8"> butter </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> Butter</span><span style="color:#ECEBE8">(&#x3C;</span><span style="color:#A1C1E4">YOUR</span><span style="color:#EDCC95"> API</span><span style="color:#EDCC95"> KEY</span><span style="color:#EDCC95"> HERE</span><span style="color:#ECEBE8">>);</span></span>
<span class="line"></span>
<span class="line"><span style="color:#ECEBE8">export default butter;</span></span></code></pre></figure>
<p>Make sure to insert your own API key. That’s all you need to start communicating with the Butter API.</p>
<h4 id="usebutter">useButter</h4>
<p>In the same <em>src</em> directory create a file called <em>useButter.js</em>, where our hook will live. Go ahead and add this basic skeleton:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> butter </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> './butter-client'</span><span style="color:#ECEBE8">;</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> useButter</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"></span>
<span class="line"><span style="color:#ECEBE8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">export</span><span style="color:#A1C1E4"> default</span><span style="color:#ECEBE8"> useButter;</span></span></code></pre></figure>
<p>We now need to add the functionality of our hook. Recall that we decided to return the API response and control variables that determine if the API is loading or if it failed. It makes sense to create them as state variables, so add the following:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> { useState } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'react'</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> butter </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> './butter-client'</span><span style="color:#ECEBE8">;</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> useButter</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> [response, setResponse] </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> useState</span><span style="color:#ECEBE8">(</span><span style="color:#A1C1E4">null</span><span style="color:#ECEBE8">);</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> [loading, setLoading] </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> useState</span><span style="color:#ECEBE8">(</span><span style="color:#A1C1E4">false</span><span style="color:#ECEBE8">);</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> [error, setError] </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> useState</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">""</span><span style="color:#ECEBE8">);</span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">  // do something with them</span></span>
<span class="line"><span style="color:#A1C1E4">  return</span><span style="color:#ECEBE8"> { response, loading, error };</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">export</span><span style="color:#A1C1E4"> default</span><span style="color:#ECEBE8"> useButter;</span></span></code></pre></figure>
<p>We declared three different state variables, each with different initial values. In the end, we return them in the form of an object.</p>
<p>Now, I want to give the user the ability to control when to call the API. Therefore, we need to expose the API call. Let us create the <code>callAPI</code> function:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">...</span></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> callAPI</span><span style="color:#A1C1E4"> =</span><span style="color:#A1C1E4"> async</span><span style="color:#ECEBE8"> (entity, method, </span><span style="color:#A1C1E4">...</span><span style="color:#ECEBE8">options) </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  if</span><span style="color:#ECEBE8"> ( butter[entity] </span><span style="color:#A1C1E4">===</span><span style="color:#A1C1E4"> undefined</span><span style="color:#A1C1E4"> ||</span><span style="color:#ECEBE8"> </span></span>
<span class="line"><span style="color:#ECEBE8">       butter[entity][method] </span><span style="color:#A1C1E4">===</span><span style="color:#A1C1E4"> undefined</span><span style="color:#ECEBE8"> ) {</span></span>
<span class="line"><span style="color:#EDCC95">    setError</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">`Unable to call method ${</span><span style="color:#97CCAE">method</span><span style="color:#97CCAE">} from entity ${</span><span style="color:#97CCAE">entity</span><span style="color:#97CCAE">}`</span><span style="color:#ECEBE8">);</span></span>
<span class="line"><span style="color:#A1C1E4">    return</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#ECEBE8">  }</span></span>
<span class="line"><span style="color:#EDCC95">  setError</span><span style="color:#ECEBE8">(</span><span style="color:#A1C1E4">null</span><span style="color:#ECEBE8">);</span></span>
<span class="line"><span style="color:#EDCC95">  setLoading</span><span style="color:#ECEBE8">(</span><span style="color:#A1C1E4">true</span><span style="color:#ECEBE8">);</span></span>
<span class="line"><span style="color:#A1C1E4">  try</span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">    const</span><span style="color:#ECEBE8"> response </span><span style="color:#A1C1E4">=</span><span style="color:#A1C1E4"> await</span><span style="color:#ECEBE8"> butter[entity][method](</span><span style="color:#A1C1E4">...</span><span style="color:#ECEBE8">options);</span></span>
<span class="line"><span style="color:#EDCC95">    setResponse</span><span style="color:#ECEBE8">(response);</span></span>
<span class="line"><span style="color:#ECEBE8">  } </span><span style="color:#A1C1E4">catch</span><span style="color:#ECEBE8"> (e) {</span></span>
<span class="line"><span style="color:#EDCC95">    setError</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">`${</span><span style="color:#97CCAE">e.status</span><span style="color:#97CCAE">}: ${</span><span style="color:#97CCAE">e.statusText</span><span style="color:#97CCAE">}`</span><span style="color:#ECEBE8">);</span></span>
<span class="line"><span style="color:#ECEBE8">  }</span></span>
<span class="line"><span style="color:#EDCC95">  setLoading</span><span style="color:#ECEBE8">(</span><span style="color:#A1C1E4">false</span><span style="color:#ECEBE8">);  </span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span>
<span class="line"><span style="color:#A1C1E4">...</span></span></code></pre></figure>
<p>Recall that the butter client needs an <em>entity</em> and a <em>method</em> (e.g. <em>post</em> and <em>list</em>). The above code checks if, for a given <em>entity</em> and <em>method</em>, the function exists (setting an error if not true). After, we change the state to inform that the API is loading and await the response from the API, we make sure we pass the correct options to the butter client. If it fails, we set the error message and if it works, we set the response. Pretty neat.</p>
<p>The complete code for the hook is:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> { useState } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'react'</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> butter </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> './butter-client'</span><span style="color:#ECEBE8">;</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> useButter</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> [response, setResponse] </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> useState</span><span style="color:#ECEBE8">(</span><span style="color:#A1C1E4">null</span><span style="color:#ECEBE8">);</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> [loading, setLoading] </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> useState</span><span style="color:#ECEBE8">(</span><span style="color:#A1C1E4">false</span><span style="color:#ECEBE8">);</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> [error, setError] </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> useState</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">""</span><span style="color:#ECEBE8">);</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#EDCC95"> callAPI</span><span style="color:#A1C1E4"> =</span><span style="color:#A1C1E4"> async</span><span style="color:#ECEBE8"> (entity, method, </span><span style="color:#A1C1E4">...</span><span style="color:#ECEBE8">options) </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">    if</span><span style="color:#ECEBE8"> ( butter[entity] </span><span style="color:#A1C1E4">===</span><span style="color:#A1C1E4"> undefined</span><span style="color:#A1C1E4"> ||</span><span style="color:#ECEBE8"> </span></span>
<span class="line"><span style="color:#ECEBE8">         butter[entity][method] </span><span style="color:#A1C1E4">===</span><span style="color:#A1C1E4"> undefined</span><span style="color:#ECEBE8"> ) {</span></span>
<span class="line"><span style="color:#EDCC95">      setError</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">`Unable to call method ${</span><span style="color:#97CCAE">method</span><span style="color:#97CCAE">} from entity ${</span><span style="color:#97CCAE">entity</span><span style="color:#97CCAE">}`</span><span style="color:#ECEBE8">);</span></span>
<span class="line"><span style="color:#A1C1E4">      return</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#ECEBE8">    }</span></span>
<span class="line"><span style="color:#EDCC95">    setError</span><span style="color:#ECEBE8">(</span><span style="color:#A1C1E4">null</span><span style="color:#ECEBE8">);</span></span>
<span class="line"><span style="color:#EDCC95">    setLoading</span><span style="color:#ECEBE8">(</span><span style="color:#A1C1E4">true</span><span style="color:#ECEBE8">);</span></span>
<span class="line"><span style="color:#A1C1E4">    try</span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">      const</span><span style="color:#ECEBE8"> response </span><span style="color:#A1C1E4">=</span><span style="color:#A1C1E4"> await</span><span style="color:#ECEBE8"> butter[entity][method](</span><span style="color:#A1C1E4">...</span><span style="color:#ECEBE8">options);</span></span>
<span class="line"><span style="color:#EDCC95">      setResponse</span><span style="color:#ECEBE8">(response);</span></span>
<span class="line"><span style="color:#ECEBE8">    } </span><span style="color:#A1C1E4">catch</span><span style="color:#ECEBE8"> (e) {</span></span>
<span class="line"><span style="color:#EDCC95">      setError</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">`${</span><span style="color:#97CCAE">e.status</span><span style="color:#97CCAE">}: ${</span><span style="color:#97CCAE">e.statusText</span><span style="color:#97CCAE">}`</span><span style="color:#ECEBE8">);</span></span>
<span class="line"><span style="color:#ECEBE8">    }</span></span>
<span class="line"><span style="color:#EDCC95">    setLoading</span><span style="color:#ECEBE8">(</span><span style="color:#A1C1E4">false</span><span style="color:#ECEBE8">);  </span></span>
<span class="line"><span style="color:#ECEBE8">  }</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">  return</span><span style="color:#ECEBE8"> [{ response, loading, error }, callAPI];</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">export</span><span style="color:#A1C1E4"> default</span><span style="color:#ECEBE8"> useButter;</span></span></code></pre></figure>
<p>Notice that we need to make <code>callAPI</code> available in the component, so we pass it alongside with the state object in the form of an array.</p>
<p>This should be enough for us to start hooking things around.</p>
<h3 id="hooking-up">Hooking up</h3>
<p>With our hook ready it is time to finally see it in action. Go to <code>App.js</code> and add the following:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> React, { useEffect } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'react'</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> useButter </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> './useButter'</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#97CCAE"> './App.css'</span><span style="color:#ECEBE8">;</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">function</span><span style="color:#EDCC95"> App</span><span style="color:#ECEBE8">() {</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> [{ response, loading, error }, callAPI] </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> useButter</span><span style="color:#ECEBE8">();</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">  useEffect</span><span style="color:#ECEBE8">(() </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#EDCC95">    callAPI</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'post'</span><span style="color:#ECEBE8">, </span><span style="color:#97CCAE">'list'</span><span style="color:#ECEBE8">, { page: </span><span style="color:#97CCAE">1</span><span style="color:#ECEBE8">, page_size: </span><span style="color:#97CCAE">10</span><span style="color:#ECEBE8"> });</span></span>
<span class="line"><span style="color:#ECEBE8">  }, []);</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">  return</span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#EDCC95"> className</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"container"</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">h1</span><span style="color:#ECEBE8">>useButter Example&#x3C;/</span><span style="color:#A1C1E4">h1</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      {loading </span><span style="color:#A1C1E4">&#x26;&#x26;</span><span style="color:#ECEBE8"> &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">>Loading from API...&#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">>}</span></span>
<span class="line"><span style="color:#ECEBE8">      {error </span><span style="color:#A1C1E4">&#x26;&#x26;</span><span style="color:#ECEBE8"> &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">>There was an error: {error}&#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">>}</span></span>
<span class="line"><span style="color:#ECEBE8">      {response </span><span style="color:#A1C1E4">&#x26;&#x26;</span><span style="color:#A1C1E4"> !</span><span style="color:#ECEBE8">error </span><span style="color:#A1C1E4">&#x26;&#x26;</span><span style="color:#A1C1E4"> !</span><span style="color:#ECEBE8">loading </span><span style="color:#A1C1E4">&#x26;&#x26;</span><span style="color:#ECEBE8"> &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;</span><span style="color:#A1C1E4">h2</span><span style="color:#ECEBE8">>Posts List&#x3C;/</span><span style="color:#A1C1E4">h2</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;</span><span style="color:#A1C1E4">ul</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">          {</span><span style="color:#EDCC95">response.data.data.map</span><span style="color:#ECEBE8">((post, i) </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">            &#x3C;</span><span style="color:#A1C1E4">li</span><span style="color:#EDCC95"> key</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{i}>{post.title}&#x3C;/</span><span style="color:#A1C1E4">li</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">          ))}</span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;/</span><span style="color:#A1C1E4">ul</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">>}</span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">  );</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">export</span><span style="color:#A1C1E4"> default</span><span style="color:#ECEBE8"> App;</span></span></code></pre></figure>
<p>If you save your project and run yarn start you will see your hook in action. Congratulations!</p>
<figure class="image"><img alt="First hook example" loading="lazy" decoding="async" width="423" height="281" src="https://rafaelquintanilha.com/_astro/ButterCMS---First-Hook-Example.BB59P0PS_lEXRY.webp"><figcaption>First hook example</figcaption></figure>
<p>Notice that it loads all posts that I have saved in my account at this moment. Yours will vary.</p>
<p>Remember that I left the usage of the hook to the user. We did this by calling the API after the first render:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">const</span><span style="color:#ECEBE8"> [{ response, loading, error }, callAPI] </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> useButter</span><span style="color:#ECEBE8">();</span></span>
<span class="line"><span style="color:#EDCC95">useEffect</span><span style="color:#ECEBE8">(() </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#EDCC95">  callAPI</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'post'</span><span style="color:#ECEBE8">, </span><span style="color:#97CCAE">'list'</span><span style="color:#ECEBE8">, { page: </span><span style="color:#97CCAE">1</span><span style="color:#ECEBE8">, page_size: </span><span style="color:#97CCAE">10</span><span style="color:#ECEBE8"> });</span></span>
<span class="line"><span style="color:#ECEBE8">}, []);</span></span></code></pre></figure>
<p>What if we want to make the <code>page_size</code> configurable? Let’s go ahead and add an input to control this value. First, include the <code>useState</code> hook:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> React, { useEffect, useState } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'react'</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#A1C1E4">...</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">function</span><span style="color:#EDCC95"> App</span><span style="color:#ECEBE8">() {</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> [pageSize, setPageSize] </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> useState</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">10</span><span style="color:#ECEBE8">);</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> [{ response, loading, error }, callAPI] </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> useButter</span><span style="color:#ECEBE8">();</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">  useEffect</span><span style="color:#ECEBE8">(() </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#EDCC95">    callAPI</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'post'</span><span style="color:#ECEBE8">, </span><span style="color:#97CCAE">'list'</span><span style="color:#ECEBE8">, { page: </span><span style="color:#97CCAE">1</span><span style="color:#ECEBE8">, page_size: pageSize });</span></span>
<span class="line"><span style="color:#ECEBE8">  }, [pageSize]);</span></span>
<span class="line"><span style="color:#A1C1E4">  ...</span></span></code></pre></figure>
<p>Now our effect will re-run every time <code>pageSize</code> changes (once it is in the dependency array). Let’s add the appropriate UI:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">...</span></span>
<span class="line"><span style="color:#A1C1E4">return</span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">  &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#EDCC95"> className</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"container"</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;</span><span style="color:#A1C1E4">h1</span><span style="color:#ECEBE8">>useButter Example&#x3C;/</span><span style="color:#A1C1E4">h1</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">    {loading </span><span style="color:#A1C1E4">&#x26;&#x26;</span><span style="color:#ECEBE8"> &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">>Loading from API...&#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">>}</span></span>
<span class="line"><span style="color:#ECEBE8">    {error </span><span style="color:#A1C1E4">&#x26;&#x26;</span><span style="color:#ECEBE8"> &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">>There was an error: {error}&#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">>}</span></span>
<span class="line"><span style="color:#ECEBE8">    {response </span><span style="color:#A1C1E4">&#x26;&#x26;</span><span style="color:#A1C1E4"> !</span><span style="color:#ECEBE8">error </span><span style="color:#A1C1E4">&#x26;&#x26;</span><span style="color:#A1C1E4"> !</span><span style="color:#ECEBE8">loading </span><span style="color:#A1C1E4">&#x26;&#x26;</span><span style="color:#ECEBE8"> &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">h2</span><span style="color:#ECEBE8">>Posts List&#x3C;/</span><span style="color:#A1C1E4">h2</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">ul</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">        {</span><span style="color:#EDCC95">response.data.data.map</span><span style="color:#ECEBE8">((post, i) </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">          &#x3C;</span><span style="color:#A1C1E4">li</span><span style="color:#EDCC95"> key</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{i}>{post.title}&#x3C;/</span><span style="color:#A1C1E4">li</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">        ))}</span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;/</span><span style="color:#A1C1E4">ul</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;</span><span style="color:#A1C1E4">label</span><span style="color:#ECEBE8">>Page Size&#x3C;/</span><span style="color:#A1C1E4">label</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;</span><span style="color:#A1C1E4">br</span><span style="color:#ECEBE8"> /></span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;</span><span style="color:#A1C1E4">input</span></span>
<span class="line"><span style="color:#EDCC95">          autoFocus</span></span>
<span class="line"><span style="color:#EDCC95">          value</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{pageSize} </span></span>
<span class="line"><span style="color:#EDCC95">          onChange</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{e </span><span style="color:#A1C1E4">=></span><span style="color:#EDCC95"> setPageSize</span><span style="color:#ECEBE8">(e.target.value)} </span></span>
<span class="line"><span style="color:#EDCC95">          type</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"number"</span></span>
<span class="line"><span style="color:#ECEBE8">        /></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">>}</span></span>
<span class="line"><span style="color:#ECEBE8">  &#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">);</span></span>
<span class="line"><span style="color:#A1C1E4">...</span></span></code></pre></figure>
<p>Here’s the final result:</p>
<p><img alt="" loading="lazy" decoding="async" width="423" height="281" src="https://rafaelquintanilha.com/_astro/ButterCMS---Second-Hook-Example.D3TlIk7Z_2r3FxI.webp"></p>
<p>And that’s it! We have created a hook that shares logic with any component. Write once, use it everywhere.</p>
<h4 id="fixing-the-dependency-array">Fixing the dependency array</h4>
<p>If you have <a href="https://eslint.org/" rel="noopener noreferrer" target="_blank">ESLint</a> configured, you will see the following warning:</p>
<blockquote>
<p>React Hook useEffect has a missing dependency: 'callAPI'. Either include it or remove the dependency array  react-hooks/exhaustive-deps</p>
</blockquote>
<p>What exactly does that mean? Recall our <code>useEffect</code> hook:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#EDCC95">useEffect</span><span style="color:#ECEBE8">(() </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#EDCC95">  callAPI</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'post'</span><span style="color:#ECEBE8">, </span><span style="color:#97CCAE">'list'</span><span style="color:#ECEBE8">, { page: </span><span style="color:#97CCAE">1</span><span style="color:#ECEBE8">, page_size: pageSize });</span></span>
<span class="line"><span style="color:#ECEBE8">}, [pageSize]);</span></span></code></pre></figure>
<p>Notice that <code>callAPI</code> is a dependency of the effect as much as <code>pageSize</code>. Even though we don’t expect it to change, it is a good practice to list all dependencies in the dependency array. Let’s fix it:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#EDCC95">useEffect</span><span style="color:#ECEBE8">(() </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#EDCC95">  callAPI</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'post'</span><span style="color:#ECEBE8">, </span><span style="color:#97CCAE">'list'</span><span style="color:#ECEBE8">, { page: </span><span style="color:#97CCAE">1</span><span style="color:#ECEBE8">, page_size: pageSize });</span></span>
<span class="line"><span style="color:#ECEBE8">}, [callAPI, pageSize]);</span></span></code></pre></figure>
<p>If you save your project and check it, you will see that there is an infinite loop going on. What’s happening?</p>
<p>Remember that our hook returns <code>callAPI</code>. So every time we call the API, it updates the state and the hook returns a new value. But <code>callAPI</code> is a new definition of the function (even though they are essentially the same) and therefore we trigger the effect again!</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">return</span><span style="color:#ECEBE8"> [{ response, loading, error }, callAPI];</span></span></code></pre></figure>
<p>So in every state change we redefine <code>callAPI</code>.  This is something we don’t want to do. Luckily, this is the exact case where <code>useCallback</code> is valuable: we want a function to persist unless some of its dependencies change. Because <code>callAPI</code> has no dependency, we don’t need it to ever change.</p>
<p>To fix this, go back to <code>useButter.js</code>, make sure you add <code>useCallback</code> along with <code>useState</code> and change the return statement to:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">return</span><span style="color:#ECEBE8"> [{ response, loading, error }, </span><span style="color:#EDCC95">useCallback</span><span style="color:#ECEBE8">(callAPI, [])];</span></span></code></pre></figure>
<p>And that’s it! Now <code>callAPI</code> won’t be redefined at every render. Save and see that it is working again.</p>
<h1 id="wrapping-up">Wrapping up</h1>
<p>In this article we learned what Hooks are and that they are meant to solve problems that have been a pebble in the shoes of the React community for a long time — how to easily reuse logic in between components instead of UI.</p>
<p>Hooks are an alternative to Higher-Order Components and Render Props, both with their pros and cons. Moreover, Hooks provide a way to map behaviors of class components to functional components (though they do not map directly).</p>
<p>Even though you can do (almost) everything classes do with Hooks, you don’t need to switch right away. Instead, try playing around with it until you feel comfortable. Although this is always a matter of personal opinion, I’d say Hooks are here to stay, not because of the hype, but ultimately because they are <em>better</em>.</p>
<p>Finally, we saw how to create your own Hook. <code>useButter</code> is an alternative to reuse logic when injecting <a href="http://buttercms.com/" rel="noopener noreferrer" target="_blank">ButterCMS</a> data in your application. It makes accessing the API trivial and handles network requests. There is still room for improvement, so feel free to tweak my code and <a href="https://github.com/rafaelquintanilha/butter-hooks-example" rel="noopener noreferrer" target="_blank">contribute in GitHub</a>!</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[Adding a Blog Into an Existing Site]]></title>
<description><![CDATA[A guide for CMS integration with ButterCMS.]]></description>
<link>https://rafaelquintanilha.com/adding-a-blog-into-an-existing-site/</link>
<guid isPermaLink="false">63704b9442a473003d9dc9f3</guid>
<category><![CDATA[React]]></category><category><![CDATA[ButterCMS]]></category><category><![CDATA[SEO]]></category>
<dc:creator><![CDATA[Rafael Quintanilha]]></dc:creator>
<pubDate>Thu, 06 Jun 2019 03:00:00 GMT</pubDate>

<content:encoded><![CDATA[<p>Consider the following scenario: you have a fully-functional website, and you want to add a blog to it. The problem: you haven’t previously accounted for this, and you start wondering what the best solution may be that won’t require a major rewrite of your working app.</p>
<p>Perhaps your website is instead still under development, but all solutions for adding blogging functionality seem difficult to fit in your current stack.</p>
<p>Sound familiar?</p>
<p>You may be a good candidate for CMS (Content Management System) integration for your app or website. CMS integration is simply taking your existing website/web app and integrating a Content Management System with it <em>without</em> having to resort to a complex monolithic solution like WordPress. It is the degree of freedom you are looking for in order to keep your tech stack of choice and still be able to enjoy the best of what a Content Management System can offer.</p>
<p>In other words, <strong>CMS integration is how to add CMS capabilities into an existing website</strong>. This article aims to explain more of it in practice, what the pain points are, how to solve them, and how you can efficiently add a CMS into your current project without needing to rewrite everything from scratch.</p>
<h2 id="challenges-of-cms-integration">Challenges of CMS Integration</h2>
<p>Traditional CMS solutions, like WordPress, have historically evolved into whole solutions controlling everything for your app or website. It means that your app will most likely live as a “monolith”, a single unit of technology that is supposed to control the entirety of your website.</p>
<p>This might be fine until it isn’t anymore. Suppose you grow tired of WordPress and want to change the CMS provider. After all, you are likely to encounter scalability issues with a monolithic solution as it grows. You now have a problem, as you will need to rebuild core parts of your app that might not even be related to the CMS. Or maybe you are an experienced developer who likes to write web apps using your preferred tech stack, but requires an easy interface for non-technical content creators and editors to be able to add and edit content without needing you to update code.</p>
<p>Historically, CMS solutions are tightly coupled to the app. You can minimize the impact of an eventual change in the future by early planning, but the reality is that you won’t always be able to foresee the need for it - and even if you do, current approaches are just suboptimal, as we will see next.</p>
<h3 id="the-subdomain-approach">The Subdomain Approach</h3>
<p>A way to circumvent the constraints imposed by a monolith solution is to move your blog to a different subdomain, such as <strong>blog</strong>.example.com. By doing this you can set up your CMS and still keep your favorite tech stack. For example, you might have a website built with Angular + NodeJS and install a WordPress blog in another subdomain.</p>
<p>While this works there are some caveats with this approach:</p>
<ol>
<li><strong>SEO</strong>. The main issue is that setting up your blog under a subdomain <a href="https://buttercms.com/blog/blog-subdomain-or-subdirectory-hint-one-is-40-better" rel="noopener noreferrer" target="_blank">can negatively impact your SEO</a>. For content that depends on organic searches, this is very undesirable.</li>
<li><strong>UI consistency</strong>. You will be tasked with the extra work of maintaining a consistent UI for two separate apps, so you don’t confuse your users. As naive as it is, consider the case where you have developed a layout for your web app and now need to find (or develop) a WordPress theme that resembles it.</li>
<li><strong>Multiple apps overhead</strong>. instead of one, you will have two applications to maintain. In the long run, this may cause a lot of headaches.</li>
</ol>
<h3 id="the-subdirectory-approach">The Subdirectory Approach</h3>
<p>An alternative to subdomains is to use subdirectories. In fact, subdirectories mitigate the major issues presented by subdomains. First, <a href="https://buttercms.com/blog/blog-subdomain-or-subdirectory-hint-one-is-40-better" rel="noopener noreferrer" target="_blank">they are SEO friendly</a>. Also, they are still part of the same app, just installed in a different directory. This structure softens the multi-app and multi-UI overhead.</p>
<p>The problem is that setting a CMS in a subdirectory can be technically challenging. It is definitely non-trivial to orchestrate everything together. A DevOps problem is something you certainly don’t want to foster.</p>
<h3 id="what-then">What Then?</h3>
<p>Both approaches have in common a considerable integration effort. Moreover, you don’t fully decouple your app from the CMS, meaning that they coexist in a clunky way. A truly good solution should neutralize integration risks and have minimal impact on the current architecture, especially from a DevOps perspective. This is something a headless CMS enables you to do.</p>
<h2 id="a-conceptual-overview-of-cms-integration">A Conceptual Overview of CMS Integration</h2>
<p>A headless CMS is a back-end content repository that makes content accessible via API. This approach allows you to treat content as you would treat any regular piece of data.</p>
<h3 id="content-as-data">Content as Data</h3>
<p>Suppose that you want to integrate your app with Google Maps. You do not want to make any styling changes, you should not set up any other servers, and you should keep everything in the same domain without creating a new directory. How is this possible?</p>
<p>This happens because you assume whatever geolocalization data you might need will be fetched in a predictable way from a 3rd-party application. Hence all you need to do is to prepare to receive that piece of information and display it accordingly. For instance, putting a marker on a map given a set of coordinates.</p>
<p>Traditional CMS solutions already perform these operations, but only for internal consumption. WordPress will save your content in the database and retrieve it when necessary, without exposing it to other applications. The way your layout or themes consume this data is different from what a regular API does, because you need to use framework-specific methods. These methods add one more layer of complexity, no matter how thorough you find their documentation.</p>
<p>This is precisely how a solution like Butter can help. ButterCMS, a headless CMS, allows you to create content normally in a separate environment, as it should be, and consume content directly in your app through an API. The end result is your content being managed as regular data, fetched from Butter’s servers and rendered as you wish, without changing the architecture of your app.</p>
<figure class="image"><img alt="Headless CMS diagram" loading="lazy" decoding="async" width="596" height="411" src="https://rafaelquintanilha.com/_astro/headless-cms-with-data-min.S8VZBJOR_2nf80B.webp"><figcaption>Headless CMS diagram</figcaption></figure>
<p>Using content as data means that you need to be language agnostic, i.e. you should be able to grab your content regardless of your tech stack. <a href="https://buttercms.com/api-first-cms/" rel="noopener noreferrer" target="_blank">Butter currently supports all major languages</a>, so you can throw it at your app today and start blogging at once.</p>
<p>In the next section, we will see how it works in practice by adding a blog into a regular website.</p>
<h2 id="cms-integration-in-practice">CMS Integration in Practice</h2>
<p>Now that we understand what CMS integration means, let us see how one can do it. For the sake of this tutorial, I will be using React but as I mentioned earlier, you can work with your favorite stack. Go ahead and <a href="https://buttercms.com/blog-engine/" rel="noopener noreferrer" target="_blank">check all available APIs on the ButterCMS website</a> if you haven’t done that before.</p>
<p>In our example, let us assume that we have an existing website and our goal is to add a blog into it. Here’s how it looks like before we add any Butter.</p>
<figure class="image"><img alt="Simple website with no blog content." loading="lazy" decoding="async" width="776" height="827" src="https://rafaelquintanilha.com/_astro/simple-app.BEYqVaWD_Z1XzqoX.webp"><figcaption>Simple website with no blog content.</figcaption></figure>
<p>There is nothing fancy on the site right now. It’s just a regular website with some dummy content. You can follow this tutorial by <a href="https://github.com/rafaelquintanilha/butter-example/tree/without-butter" rel="noopener noreferrer" target="_blank">checking this GitHub repo</a>. This project was bootstrapped with <a href="https://facebook.github.io/create-react-app/" rel="noopener noreferrer" target="_blank">Create React App</a>. For simplicity I’ll omit CSS changes but the main file can be inspected <a href="https://github.com/rafaelquintanilha/butter-example/blob/master/src/App.css" rel="noopener noreferrer" target="_blank">here</a>.</p>
<h3 id="adding-the-router">Adding the Router</h3>
<p>Let’s add a page that will hold our blog content and will work as a subdirectory. As explained before, this approach improves SEO. For this, we will need <a href="https://reacttraining.com/react-router/web/guides/quick-start" rel="noopener noreferrer" target="_blank">React Router</a>. In your app directory open the terminal and type:</p>
<figure class="code"><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="plaintext"><code><span class="line"><span>yarn react-router-dom</span></span></code></pre></figure>
<p>Or alternatively:</p>
<figure class="code"><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="plaintext"><code><span class="line"><span>npm i --save react-router-dom</span></span></code></pre></figure>
<p>To simplify the code, I’ll break our home down into three different components. Here is how <em>App.js</em> looks like:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> React, { Component } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'react'</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#97CCAE"> './App.css'</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> Home </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> './Home'</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> Header </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> './Header'</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> Footer </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> './Footer'</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">class</span><span style="color:#EDCC95"> App</span><span style="color:#A1C1E4"> extends</span><span style="color:#ECEBE8"> Component {</span></span>
<span class="line"><span style="color:#EDCC95">  render</span><span style="color:#ECEBE8">() {</span></span>
<span class="line"><span style="color:#A1C1E4">    return</span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#EDCC95"> className</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"container"</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;</span><span style="color:#A1C1E4">Header</span><span style="color:#ECEBE8"> /></span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;</span><span style="color:#A1C1E4">Home</span><span style="color:#ECEBE8"> /></span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;</span><span style="color:#A1C1E4">Footer</span><span style="color:#ECEBE8"> /></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">    )</span></span>
<span class="line"><span style="color:#ECEBE8">  }</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">export</span><span style="color:#A1C1E4"> default</span><span style="color:#ECEBE8"> App</span></span></code></pre></figure>
<p>Now, we want to be able to render either <code>Home</code> or the list of blog posts. We will then replace Home with the router and make sure that the main element is common to all routes:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#ECEBE8">…</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#ECEBE8">  BrowserRouter </span><span style="color:#A1C1E4">as</span><span style="color:#ECEBE8"> Router,</span></span>
<span class="line"><span style="color:#ECEBE8">  Route,</span></span>
<span class="line"><span style="color:#ECEBE8">  Switch</span></span>
<span class="line"><span style="color:#ECEBE8">} </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'react-router-dom'</span><span style="color:#ECEBE8">;</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">class</span><span style="color:#EDCC95"> App</span><span style="color:#A1C1E4"> extends</span><span style="color:#ECEBE8"> Component {</span></span>
<span class="line"><span style="color:#EDCC95">  render</span><span style="color:#ECEBE8">() {</span></span>
<span class="line"><span style="color:#A1C1E4">    return</span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#EDCC95"> className</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"container"</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;</span><span style="color:#A1C1E4">Router</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">          &#x3C;</span><span style="color:#A1C1E4">Header</span><span style="color:#ECEBE8"> /></span></span>
<span class="line"><span style="color:#ECEBE8">          &#x3C;</span><span style="color:#A1C1E4">main</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">            &#x3C;</span><span style="color:#A1C1E4">Switch</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">              &#x3C;</span><span style="color:#A1C1E4">Route</span><span style="color:#EDCC95"> exact</span><span style="color:#EDCC95"> path</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"/"</span><span style="color:#EDCC95"> component</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{Home} /></span></span>
<span class="line"><span style="color:#ECEBE8">            &#x3C;/</span><span style="color:#A1C1E4">Switch</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">          &#x3C;/</span><span style="color:#A1C1E4">main</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">          &#x3C;</span><span style="color:#A1C1E4">Footer</span><span style="color:#ECEBE8"> /></span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;/</span><span style="color:#A1C1E4">Router</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">    );</span></span>
<span class="line"><span style="color:#ECEBE8">  }</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span>
<span class="line"><span style="color:#ECEBE8">…</span></span></code></pre></figure>
<p>Save and check your progress by running <code>npm start</code> and going to <a href="http://localhost:3000" rel="noopener noreferrer" target="_blank">http://localhost:3000</a>. You will see that your app loads normally but if you change the URL to <a href="http://localhost:3000/blog" rel="noopener noreferrer" target="_blank">http://localhost:3000/blog</a> an empty space will be rendered. Let’s fix that!</p>
<h3 id="adding-the-blog-page">Adding the Blog Page</h3>
<p>Once the router is all set, let us create a dummy page which we will use to hold the blog content in just a moment. Go ahead and create a file called <em>Blog.js</em>, adding this code:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> React </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'react'</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> Blog</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  return</span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">h1</span><span style="color:#ECEBE8">>Blog&#x3C;/</span><span style="color:#A1C1E4">h1</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">  )</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">export</span><span style="color:#A1C1E4"> default</span><span style="color:#ECEBE8"> Blog</span></span></code></pre></figure>
<p>Now it’s time to make our router aware of this new page. In <em>App.js</em>:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">...</span></span>
<span class="line"><span style="color:#ECEBE8">&#x3C;</span><span style="color:#A1C1E4">main</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">  &#x3C;</span><span style="color:#A1C1E4">Switch</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;</span><span style="color:#A1C1E4">Route</span><span style="color:#EDCC95"> exact</span><span style="color:#EDCC95"> path</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"/"</span><span style="color:#EDCC95"> component</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{Home} /></span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;</span><span style="color:#A1C1E4">Route</span><span style="color:#EDCC95"> exact</span><span style="color:#EDCC95"> path</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"/blog"</span><span style="color:#EDCC95"> component</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{Blog} /></span></span>
<span class="line"><span style="color:#ECEBE8">  &#x3C;/</span><span style="color:#A1C1E4">Switch</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">&#x3C;/</span><span style="color:#A1C1E4">main</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#A1C1E4">...</span></span></code></pre></figure>
<p>We need a way to allow users to visit the blog page without needing to manually change the URL. Let’s fix that in <em>Header.js</em>:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> React </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'react'</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> { Link } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'react-router-dom'</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> Header</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">  &#x3C;</span><span style="color:#A1C1E4">header</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;</span><span style="color:#A1C1E4">nav</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#EDCC95"> className</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"logo"</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;</span><span style="color:#A1C1E4">Link</span><span style="color:#EDCC95"> to</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"/"</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">          Fine Coffee{</span><span style="color:#97CCAE">' '</span><span style="color:#ECEBE8">}</span></span>
<span class="line"><span style="color:#ECEBE8">          &#x3C;</span><span style="color:#A1C1E4">span</span><span style="color:#EDCC95"> role</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"img"</span><span style="color:#EDCC95"> aria-label</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"Coffee"</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">            ☕</span></span>
<span class="line"><span style="color:#ECEBE8">          &#x3C;/</span><span style="color:#A1C1E4">span</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;/</span><span style="color:#A1C1E4">Link</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">ul</span><span style="color:#EDCC95"> className</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"menu"</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;</span><span style="color:#A1C1E4">li</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">          &#x3C;</span><span style="color:#A1C1E4">Link</span><span style="color:#EDCC95"> to</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"/blog"</span><span style="color:#ECEBE8">>Blog&#x3C;/</span><span style="color:#A1C1E4">Link</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;/</span><span style="color:#A1C1E4">li</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;</span><span style="color:#A1C1E4">li</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">          &#x3C;</span><span style="color:#A1C1E4">a</span><span style="color:#EDCC95"> href</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"tel:"</span><span style="color:#ECEBE8">>Call Us&#x3C;/</span><span style="color:#A1C1E4">a</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;/</span><span style="color:#A1C1E4">li</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;/</span><span style="color:#A1C1E4">ul</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;/</span><span style="color:#A1C1E4">nav</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">  &#x3C;/</span><span style="color:#A1C1E4">header</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">)</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">export</span><span style="color:#A1C1E4"> default</span><span style="color:#ECEBE8"> Header</span></span></code></pre></figure>
<p>And that’s it! You now have a subdomain all set just waiting for your blog posts:</p>
<figure class="image"><img alt="Blog routing" loading="lazy" decoding="async" width="783" height="833" src="https://rafaelquintanilha.com/_astro/cms-integration-blog-routing.CVJPKQ8y_jCnfc.webp"><figcaption>Blog routing</figcaption></figure>
<h3 id="adding-butter">Adding Butter</h3>
<p>In order to use Butter to fetch your content, you will need an API key. Go to <a href="https://buttercms.com/" rel="noopener noreferrer" target="_blank">Butter’s main page</a> and sign up for the trial in order to get one.</p>
<p>With the key in hand, create a file called <em>butter-client.js</em> under the <em>src</em> folder:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> Butter </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'buttercms'</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#ECEBE8"> butter </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> Butter</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'&#x3C;YOUR_API_KEY>'</span><span style="color:#ECEBE8">)</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">export</span><span style="color:#A1C1E4"> default</span><span style="color:#ECEBE8"> butter</span></span></code></pre></figure>
<p>Make sure to replace <code>&#x3C;YOUR_API_KEY></code> with your actual key.</p>
<p>The next step is to modify <em>Blog.js</em> in order to connect with Butter. For some extra fun I will use the new React Hooks API.</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> React, { useState, useEffect } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'react'</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> butter </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> './butter-client'</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> PostSnippet </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> './PostSnippet'</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> Blog</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> [loading, setLoading] </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> useState</span><span style="color:#ECEBE8">(</span><span style="color:#A1C1E4">false</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> [error, setError] </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> useState</span><span style="color:#ECEBE8">(</span><span style="color:#A1C1E4">false</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> [data, setData] </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> useState</span><span style="color:#ECEBE8">(</span><span style="color:#A1C1E4">null</span><span style="color:#ECEBE8">)</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#EDCC95"> fetchPosts</span><span style="color:#A1C1E4"> =</span><span style="color:#A1C1E4"> async</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#EDCC95">    setLoading</span><span style="color:#ECEBE8">(</span><span style="color:#A1C1E4">true</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#EDCC95">    setError</span><span style="color:#ECEBE8">(</span><span style="color:#A1C1E4">false</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#A1C1E4">    try</span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">      const</span><span style="color:#ECEBE8"> response </span><span style="color:#A1C1E4">=</span><span style="color:#A1C1E4"> await</span><span style="color:#EDCC95"> butter.post.list</span><span style="color:#ECEBE8">({</span></span>
<span class="line"><span style="color:#ECEBE8">        page: </span><span style="color:#97CCAE">1</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#ECEBE8">        page_size: </span><span style="color:#97CCAE">10</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#ECEBE8">      })</span></span>
<span class="line"><span style="color:#EDCC95">      setData</span><span style="color:#ECEBE8">(response.data)</span></span>
<span class="line"><span style="color:#ECEBE8">    } </span><span style="color:#A1C1E4">catch</span><span style="color:#ECEBE8"> (e) {</span></span>
<span class="line"><span style="color:#EDCC95">      setError</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">`There was an error: ${</span><span style="color:#97CCAE">e.message</span><span style="color:#97CCAE">}`</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#ECEBE8">    }</span></span>
<span class="line"><span style="color:#EDCC95">    setLoading</span><span style="color:#ECEBE8">(</span><span style="color:#A1C1E4">false</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#ECEBE8">  }</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">  useEffect</span><span style="color:#ECEBE8">(() </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#EDCC95">    fetchPosts</span><span style="color:#ECEBE8">()</span></span>
<span class="line"><span style="color:#ECEBE8">  }, [])</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#EDCC95"> getPosts</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      {</span><span style="color:#EDCC95">data.data.map</span><span style="color:#ECEBE8">((post, i) </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;</span><span style="color:#A1C1E4">PostSnippet</span><span style="color:#ECEBE8"> {</span><span style="color:#A1C1E4">...</span><span style="color:#ECEBE8">post} </span><span style="color:#EDCC95">key</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{i} /></span></span>
<span class="line"><span style="color:#ECEBE8">      ))}</span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">  )</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#EDCC95"> getContent</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">    if</span><span style="color:#ECEBE8"> (loading) </span><span style="color:#A1C1E4">return</span><span style="color:#ECEBE8"> &#x3C;</span><span style="color:#A1C1E4">p</span><span style="color:#ECEBE8">>Fetching posts...&#x3C;/</span><span style="color:#A1C1E4">p</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#A1C1E4">    if</span><span style="color:#ECEBE8"> (error) </span><span style="color:#A1C1E4">return</span><span style="color:#ECEBE8"> &#x3C;</span><span style="color:#A1C1E4">p</span><span style="color:#ECEBE8">>{error}&#x3C;/</span><span style="color:#A1C1E4">p</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#A1C1E4">    if</span><span style="color:#ECEBE8"> (</span><span style="color:#A1C1E4">!</span><span style="color:#ECEBE8">data) </span><span style="color:#A1C1E4">return</span><span style="color:#A1C1E4"> null</span></span>
<span class="line"><span style="color:#A1C1E4">    return</span><span style="color:#EDCC95"> getPosts</span><span style="color:#ECEBE8">()</span></span>
<span class="line"><span style="color:#ECEBE8">  }</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">  return</span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">h1</span><span style="color:#ECEBE8">>Blog&#x3C;/</span><span style="color:#A1C1E4">h1</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      {</span><span style="color:#EDCC95">getContent</span><span style="color:#ECEBE8">()}</span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">  )</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">export</span><span style="color:#A1C1E4"> default</span><span style="color:#ECEBE8"> Blog</span></span></code></pre></figure>
<p>The key part is the highlighted line. This is where we communicate with ButterCMS and retrieve our content. Notice that for simplicity we are fetching only the first ten posts. You can check the <a href="https://buttercms.com/docs/api/?javascript" rel="noopener noreferrer" target="_blank">API Reference</a> if you are curious about other possibilities.</p>
<p>The rest of the code is about setting up control variables and rendering the correct content. Notice that we run <code>fetchPosts()</code> only when the component mounts, which is defined by the <code>useEffect</code> hook without any dependencies (an empty array).</p>
<p>Observe that for each returned post we render the <code>PostSnippet</code> component, where we display basic information about the post such as the title, the summary, and the author’s name. Let’s move forward and create <em>PostSnippet.js</em>:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> React </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'react'</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> moment </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'moment'</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> PostSnippet</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> props </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  return</span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#EDCC95"> className</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"post-snippet"</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">h3</span><span style="color:#ECEBE8">>{props.title}&#x3C;/</span><span style="color:#A1C1E4">h3</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">p</span><span style="color:#ECEBE8">>{props.summary}&#x3C;/</span><span style="color:#A1C1E4">p</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">          By{</span><span style="color:#97CCAE">' '</span><span style="color:#ECEBE8">}</span></span>
<span class="line"><span style="color:#ECEBE8">          &#x3C;</span><span style="color:#A1C1E4">strong</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">            {props.author.first_name} {props.author.last_name}</span></span>
<span class="line"><span style="color:#ECEBE8">          &#x3C;/</span><span style="color:#A1C1E4">strong</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;</span><span style="color:#A1C1E4">span</span><span style="color:#EDCC95"> className</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"publication-date"</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">          Published on {</span><span style="color:#EDCC95">moment</span><span style="color:#ECEBE8">(props.published)</span><span style="color:#EDCC95">.format</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'YYYY-MM-DD'</span><span style="color:#ECEBE8">)}</span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;/</span><span style="color:#A1C1E4">span</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">  )</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">export</span><span style="color:#A1C1E4"> default</span><span style="color:#ECEBE8"> PostSnippet</span></span></code></pre></figure>
<p>Refer to the documentation to inspect all values returned by the API. Note the use of <a href="https://momentjs.com/" rel="noopener noreferrer" target="_blank">MomentJS</a> for formatting the date of publication.</p>
<p>Here is how your blog page should be looking now with the dummy post Butter automatically creates:</p>
<figure class="image"><img alt="Blog with post" loading="lazy" decoding="async" width="777" height="832" src="https://rafaelquintanilha.com/_astro/blog-with-post.hfqFvTjw_Z1knkmt.webp"><figcaption>Blog with post</figcaption></figure>
<p>The last step is to display the full post and have a permalink, i.e. a permanent URL, to it.</p>
<h3 id="routing-to-the-post">Routing to the Post</h3>
<p>Every post will have its own link. Let’s go back to <em>App.js</em> and add a new route:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">...</span></span>
<span class="line"><span style="color:#ECEBE8">&#x3C;</span><span style="color:#A1C1E4">Switch</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">  &#x3C;</span><span style="color:#A1C1E4">Route</span><span style="color:#EDCC95"> exact</span><span style="color:#EDCC95"> path</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"/"</span><span style="color:#EDCC95"> component</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{Home} /></span></span>
<span class="line"><span style="color:#ECEBE8">  &#x3C;</span><span style="color:#A1C1E4">Route</span><span style="color:#EDCC95"> exact</span><span style="color:#EDCC95"> path</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"/blog"</span><span style="color:#EDCC95"> component</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{Blog} /></span></span>
<span class="line"><span style="color:#ECEBE8">  &#x3C;</span><span style="color:#A1C1E4">Route</span><span style="color:#EDCC95"> path</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"/blog/:slug"</span><span style="color:#EDCC95"> render</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{Post} /></span></span>
<span class="line"><span style="color:#ECEBE8">&#x3C;/</span><span style="color:#A1C1E4">Switch</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#A1C1E4">...</span></span></code></pre></figure>
<p>This new route will be activated when the URL is in the format <a href="https://example.com/blog/my-fancy-post" rel="noopener noreferrer" target="_blank">https://example.com/blog/my-fancy-post</a> and render the <code>Post</code> component. In order to make this work, we need <code>Post</code> to have all the information needed to render the content. Let’s go back to <code>PostSnippet</code> and add a hyperlink to the title:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> PostSnippet</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> props </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  return</span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#EDCC95"> className</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"post-snippet"</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">h3</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;</span><span style="color:#A1C1E4">Link</span><span style="color:#EDCC95"> to</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{{</span></span>
<span class="line"><span style="color:#ECEBE8">          pathname: </span><span style="color:#97CCAE">`/blog/${</span><span style="color:#97CCAE">props.slug</span><span style="color:#97CCAE">}`</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#ECEBE8">          state: props</span></span>
<span class="line"><span style="color:#ECEBE8">        }}></span></span>
<span class="line"><span style="color:#ECEBE8">          {props.title}</span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;/</span><span style="color:#A1C1E4">Link</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;/</span><span style="color:#A1C1E4">h3</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      ...</span></span></code></pre></figure>
<p>Notice that we use the slug as the permalink and we pass the props contained in the snippet directly to whichever component is set to the route (in our case, <code>Post</code>). Very neat from the react-router folks!</p>
<p>Finally, it is time to create the <code>Post</code> component:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> React </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'react'</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> moment </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'moment'</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> { Link } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'react-router-dom'</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> Post</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> props </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> data </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> props.location.state</span></span>
<span class="line"><span style="color:#A1C1E4">  return</span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#EDCC95"> className</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"post"</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">h1</span><span style="color:#ECEBE8">>{data.title}&#x3C;/</span><span style="color:#A1C1E4">h1</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">hr</span><span style="color:#ECEBE8"> /></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#EDCC95"> className</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"author"</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;</span><span style="color:#A1C1E4">img</span><span style="color:#EDCC95"> src</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{data.author.profile_image} </span><span style="color:#EDCC95">alt</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"Author"</span><span style="color:#ECEBE8"> /></span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">          Published by{</span><span style="color:#97CCAE">' '</span><span style="color:#ECEBE8">}</span></span>
<span class="line"><span style="color:#ECEBE8">          &#x3C;</span><span style="color:#A1C1E4">strong</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">            {data.author.first_name} {data.author.last_name}</span></span>
<span class="line"><span style="color:#ECEBE8">          &#x3C;/</span><span style="color:#A1C1E4">strong</span><span style="color:#ECEBE8">>{</span><span style="color:#97CCAE">' '</span><span style="color:#ECEBE8">}</span></span>
<span class="line"><span style="color:#ECEBE8">          on {</span><span style="color:#EDCC95">moment</span><span style="color:#ECEBE8">(data.published)</span><span style="color:#EDCC95">.format</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'MMMM Do, YYYY'</span><span style="color:#ECEBE8">)}</span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">hr</span><span style="color:#ECEBE8"> /></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#EDCC95"> dangerouslySetInnerHTML</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{{ __html: data.body }} /></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">hr</span><span style="color:#ECEBE8"> /></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">Link</span><span style="color:#EDCC95"> to</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"/blog"</span><span style="color:#ECEBE8">></span><span style="color:#97CCAE">&#x26;larr;</span><span style="color:#ECEBE8"> Back to the posts list&#x3C;/</span><span style="color:#A1C1E4">Link</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">  )</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">export</span><span style="color:#A1C1E4"> default</span><span style="color:#ECEBE8"> Post</span></span></code></pre></figure>
<p>The data passed via the state prop of the <code>Link</code> component is accessible through <code>props.location.state</code>. This is all we need in order to display the correct content.</p>
<p>If everything went well, this is the final result:</p>
<figure class="image"><img alt="View post" loading="lazy" decoding="async" width="783" height="833" src="https://rafaelquintanilha.com/_astro/cms-integration-view-post.CQB6s5QY_GjSbm.webp"><figcaption>View post</figcaption></figure>
<h3 id="adding-content">Adding Content</h3>
<p>Once we successfully integrated the CMS into our existing website, we can easily manage the content on Butter’s side. Fortunately, there is no need to touch any code anymore - <em>and we have decoupled our app from the CMS!</em></p>
<p>To illustrate how easy adding new content can be, let’s open Butter’s admin panel, click on <em>Blog Posts</em> and create a new post by adding some content and hitting <em>Publish</em>:</p>
<figure class="image"><img alt="Butter interface" loading="lazy" decoding="async" width="1092" height="830" src="https://rafaelquintanilha.com/_astro/butter-interface.DHRFQaEH_Z1iw3Gi.webp"><figcaption>Butter interface</figcaption></figure>
<p>With the post published, go back to the app and check that it’s already there:</p>
<figure class="image"><img alt="Blog with a new post" loading="lazy" decoding="async" width="777" height="833" src="https://rafaelquintanilha.com/_astro/blog-with-new-post.C1y69cCn_ezJie.webp"><figcaption>Blog with a new post</figcaption></figure>
<p>And that’s it! Our integration is complete with minimum effort.</p>
<p>The <a href="https://github.com/rafaelquintanilha/butter-example" rel="noopener noreferrer" target="_blank">full code for this tutorial is available on GitHub</a>. There is also a <a href="https://butter-example.netlify.com/" rel="noopener noreferrer" target="_blank">live example</a> if you are curious about the end result.</p>
<h2 id="conclusion">Conclusion</h2>
<p>The web is continuously evolving resulting in obtrusive solutions that don’t play along with other technologies being pushed aside. Integration and maintainability are major concerns that need to be addressed with responsibility.</p>
<p>Treating your content as regular data gives you the flexibility you need to enjoy the power of CMS solutions without being chained to a piece of technology, as you never know when you may want to switch it in the future. Freedom of choice and fewer maintenance headaches are huge wins for developers.</p>
<p>To wrap it up, a good CMS integration should:</p>
<ul>
<li><strong>Decouple your website from the data</strong>. Both should coexist without being directly connected, in the sense that changes in one end do not affect the other end.</li>
<li><strong>Allow easy integration</strong>. A plain and simple API will do the job. Just call the API when you want to insert content from the CMS into your app.</li>
<li><strong>Have a reduced cost of change</strong>. If you ever want to change the underlying technologies that power up your application, having a CMS should not impact the complexity of the change.</li>
<li><strong>Give you freedom of tech stack</strong>. The CMS should be agnostic to whichever tech stack you decided to use in your project. They are separate entities and therefore should not interfere with each other apart from the API.</li>
</ul>]]></content:encoded>
</item>
</channel>
</rss>
