<?xml version="1.0" encoding="UTF-8"?><rss 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" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ingryd Moura on Medium]]></title>
        <description><![CDATA[Stories by Ingryd Moura on Medium]]></description>
        <link>https://medium.com/@ingrydmoura?source=rss-129e77291ab0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8QtWyVTnnW6iH7J3aqoC8Q.jpeg</url>
            <title>Stories by Ingryd Moura on Medium</title>
            <link>https://medium.com/@ingrydmoura?source=rss-129e77291ab0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 18:55:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ingrydmoura/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The new Suspense API in React 18]]></title>
            <link>https://medium.com/hurb-labs/the-new-suspense-api-in-react-18-12360c6bfe02?source=rss-129e77291ab0------2</link>
            <guid isPermaLink="false">https://medium.com/p/12360c6bfe02</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[react18]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[suspense]]></category>
            <dc:creator><![CDATA[Ingryd Moura]]></dc:creator>
            <pubDate>Mon, 06 Feb 2023 19:01:44 GMT</pubDate>
            <atom:updated>2023-02-06T19:16:41.596Z</atom:updated>
            <content:encoded><![CDATA[<h4>What is it? What does it eat? Where does it live?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KUTl5VaMcYDYTsrh_IJHhw.png" /></figure><h3>Before all… What is the Suspense API?</h3><p>An API that can be used to suspense the component execution. It is a way to show a fallback while the component is suspended.</p><p>Something like that …</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*Z3dZesDmFzAQzzIQm0Mkug.gif" /><figcaption>Loading gif.</figcaption></figure><h3>Why use it?</h3><ul><li>Code splitting</li><li>User experience</li><li>No state control to show “loading”.</li></ul><p><strong>Code splitting</strong></p><p>With <em>React.Lazy,</em> you can import a component dynamically, and it loads if necessary. <br>The bundle involves aligning the components in order and putting in a javascript code. But, as our application grows, the bundle becomes larger and turns the application slower and harder to use. <br>The bundle can be divided into smaller pieces with code splitting, and the critical part can be loaded first.</p><p><strong>User experience</strong></p><p>When applications are created, you need to consider users using slower connections. So, you need to control the user experience during the suspense timer.</p><p><strong>No state control to show “loading”.</strong></p><p>Does it look familiar to you?</p><pre>import React, { useState } from &#39;react&#39;;<br><br>const Component = () =&gt; {<br>  const [isLoading, setIsLoading] = useState(false);<br>  <br>  return (<br>    &lt;div&gt;<br>      {isLoading ? &lt;Spinner /&gt; : &lt;p&gt;Hello!&lt;/p&gt;}<br>    &lt;/div&gt;<br>  )<br>};</pre><p>Without the Suspense, you must access the isLoading state to show the “loading”. In this case, show the Spinner component when the state isLoading = true . If not, show the Hello text.</p><h3>How to use it?</h3><p>Using the Suspense, you must provide a fallback option (a React component or a string, for example). It can be many levels down in the DOM, and the fallback would show.</p><pre>import React, { lazy, Suspense } from &#39;react&#39;;<br><br>const LazyComments = lazy(() =&gt; import(&#39;./Comments&#39;));<br><br>const Component = () =&gt; (<br>    &lt;Suspense fallback={&lt;Spinner /&gt;}&gt;<br>      &lt;LazyComments /&gt;<br>    &lt;/Suspense&gt;<br>);</pre><p>In this example, theSpinner component is a fallback option and the Comments is a <em>Lazy</em> component.</p><p>Nested Suspense components can be used to improve the load process.</p><p>Look it:</p><pre>const Component = () =&gt; (<br>  &lt;Suspense fallback={&lt;RightColumnSpinner /&gt;}&gt;<br>    &lt;RightColumn&gt;<br>      &lt;SideBar /&gt;<br>    &lt;/RightColumn&gt;<br>    &lt;LeftColumn&gt;<br>      &lt;Suspense fallback={&lt;LeftColumnSpinner /&gt;}&gt;<br>        &lt;Comments /&gt;<br>        &lt;Post /&gt;<br>      &lt;/Suspense&gt;<br>    &lt;/LeftColumn&gt;<br>  &lt;/Suspense&gt;<br>);</pre><p>If SideBar is suspended, all the page is replaced with RightColumnSpinner, but if Comments or Post is suspended, both are replaced withLeftColumnSpinner .</p><h3>Legacy Suspense x Concurrent Suspense</h3><p>There are some differences between Suspense (React 16) and Suspense (React 18):</p><figure><img alt="Comparing Legacy Suspense and Concurrent Suspense. Legacy Suspense: The tree elements are mounted instantly in DOM, the tree is visually hidden when the suspense is triggered, and It throws an error when used in SSR. Concurrent Suspense: The element isn’t mounted until the suspended component is resolved, the elements tree doesn’t exist when suspense is actioned, and it’s working with SSR." src="https://cdn-images-1.medium.com/max/613/1*ENBbx1rPpRKxvbrNdtYWKQ.png" /><figcaption>Table image comparing Legacy Suspense and Concurrent Suspense.</figcaption></figure><p>Let’s see how it works in React 16 and React 18 with this example:</p><pre>const Component = () =&gt; (<br>  &lt;div&gt;<br>    {showComments &amp;&amp; (<br>      &lt;Suspense fallback={&lt;Spinner /&gt;}&gt;<br>        &lt;Panel&gt;<br>          &lt;Comments /&gt;<br>        &lt;/Panel&gt;<br>      &lt;/Suspense&gt;<br>    )}<br>  &lt;/div&gt;<br>);</pre><p>If showComments changes from false to true, React starts to render the Panel content but &lt;Comments /&gt; is suspended. In this case, the &lt;Panel /&gt; doesn’t appear because all content wrapped by the nearest Suspense is hidden until the DOM tree is ready.</p><p>So, these are the components that I created above.</p><figure><img alt="The Panel component has the Comments component inside it." src="https://cdn-images-1.medium.com/max/421/1*zbilFGUeoeyCCli9j0znjQ.png" /><figcaption>Image of component Panel and inside it the component Comments.</figcaption></figure><h4>In React 16:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*64LTdZrOH-LAiNRMkQMdTQ.png" /><figcaption>Image of the steps of suspense in React 16.</figcaption></figure><p><strong>Steps</strong></p><ol><li>Put the &lt;Panel /&gt; in DOM, but with a “space” instead of&lt;Comments /&gt;</li><li>Add display: none in &lt;Panel /&gt; to hide</li><li>Add &lt;Spinner /&gt; in the DOM</li><li>Wait &lt;Comments /&gt; until it is ready</li><li>Try to render again</li><li>Remove &lt;Spinner /&gt; from DOM</li><li>Put &lt;Comments /&gt; inside &lt;Panel /&gt; (is still hidden)</li><li>Remove display: none from the&lt;Panel /&gt;</li></ol><h4>Now, in React 18:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*d3jhtjsCi_yiOkZhFXwTiw.png" /><figcaption>Image of the steps of suspense in React 18.</figcaption></figure><p><strong>Steps</strong></p><ol><li>Remove the &lt;Panel /&gt; from the DOM</li><li>Add &lt;Spinner /&gt; in the DOM</li><li>Wait &lt;Comments /&gt; until it is ready</li><li>Try to render again</li><li>Remove &lt;Spinner /&gt; from DOM</li><li>Put &lt;Panel /&gt; with &lt;Comments /&gt; in the DOM</li></ol><h3>Suspense in SSR</h3><p>If you don’t know about SSR(Server Side Rendering) yet, I recommend <a href="https://www.patterns.dev/posts/server-side-rendering/#:~:text=Server%2Dside%20rendering%20(SSR),are%20handled%20on%20the%20server.">this explanation</a> to help you understand better.</p><p>SSR applications have some steps:</p><figure><img alt="Steps: Fetch data for the application (server), renders the app to HTML and send it in the response (server), load the JS code for the app (client), and connect the JS logic into the HTML generated by the server for the app (client)." src="https://cdn-images-1.medium.com/max/742/1*-Ea0AmACTaaB0sF8sI-GIg.png" /><figcaption>Image of the SSR steps.</figcaption></figure><p>It is essential to know that each step has to finish the whole application in one go before the next stage starts.<br>This isn’t efficient if some parts of the app are slower than others.<br>React 18 allows &lt;Suspense /&gt; split your app into smaller independent units that will go through those steps independently and not block the rest of the app.<br>As a result, users will see the content sooner and will be able to start interacting with it faster. The slower parts of your app will not “drag” on the faster parts.<br>This also o means that React.lazy works with SSR now. Before, if a component was suspended during server rendering, an error occurred, so apps couldn’t use Suspense.</p><h4>SSR problems</h4><ul><li><strong>Problem 1: Search for everything before you can show anything</strong></li></ul><p>A problem with SSR today is that it doesn’t allow components to wait for data. So when the HTML renders, you should already have all the data for your components on the server. This means you must collect all the server data before sending any HTML to the client.</p><p>For example, we are rendering a post with comments. <br>The comments are essential to display first, so you want to include them in the HTML output of the server. But your API is slow, and you don’t have control over this.</p><p>Now, you have two difficult choices:<br>- Exclude the data from the server output, but the user won’t see the data until de javascript is loaded.<br>- Include the data from the server output, but delay sending the rest of the HTML until the comments are loaded and the entire tree can be rendered.</p><p><strong>Solution</strong></p><p>Wrap part of the code with &lt;Suspense /&gt; .</p><pre>const Component = () =&gt; (<br>  &lt;&gt;<br>     &lt;Navbar /&gt;<br>     &lt;Suspense fallback={&lt;Spinner /&gt;}&gt;<br>       &lt;Comments /&gt;<br>     &lt;/Suspense&gt;<br>  &lt;/&gt;<br>);</pre><p>In this case, React should display the &lt;Spinner /&gt; until the &lt;Comments /&gt; is ready.<br>By wrapping &lt;Comments /&gt; in &lt;Suspense /&gt;, React doesn’t have to wait for the comments to start transmitting the HTML to the rest of the page. Instead, send the placeholder (a spinner) instead of the comments.<br>Initially, the comments are not in the HTML.<br>When the comments data is ready on the server, we will send additional HTML to the same stream to put it in the correct position.<br>As a result, the delayed HTML for comments will appear before React is loaded on the client.<br>This way, it is unnecessary to fetch all the data before showing anything.<br>If some part of the screen delays the initial HTML, you don’t need to choose between delaying all HTML or removing it from the server’s HTML. Instead, you can allow that part to appear later in the HTML flow.</p><ul><li><strong>Problem 2: Load for everything before you can hydrate anything</strong></li></ul><p>After that javascript code is loaded, and the HTML will go hydrated, turning interactive. The React will run the HTML generated from the server while rendering the components and attaching event handlers. And to this to work, the DOM tree produced in the browser must correspond to the tree on the server. Otherwise, you can’t match them! <br>One consequence is that you must load JavaScript for all components in the client before you can start hydrating any of them.</p><p>For example, a comment widget has complex interaction logic and takes time to load JavaScript.</p><p>It would be great to render the comments on the server for the HTML to show them to the user first. But, the hydration can only be done at one time; we can’t hydrate the navigation bar or sidebar or post content until to load the code for the comment widget.</p><p><strong>Solution</strong></p><p>To use React.lazy().</p><pre>import React, { lazy, Suspense } from &#39;react&#39;;<br><br>const LazyComments = lazy(() =&gt; import(&#39;./Comments&#39;));<br><br>const Component = () =&gt; (<br>    &lt;Suspense fallback={&lt;Spinner /&gt;}&gt;<br>      &lt;LazyComments /&gt;<br>    &lt;/Suspense&gt;<br>);</pre><p>We can upload the initial HTML first, but there is a problem: once the code javascript is loaded, it is impossible to start to hydrate the application on the client, and if the size code is large, it can take a while.<br>You use code splitting to avoid large bundlers and separate the comment code from the main bundler. In this case, you specify the code that doesn’t need to be loaded synchronously, and the bundler will split it into a separate script tag.<br>Before, this didn’t work in server rendering. Now, in React 18, the Suspense allows hydrating the application before the comments widget is loaded.<br>When &lt;Comments /&gt; it is wrapped in the &lt;Suspense /&gt;, React doesn’t block the rest of the page while it is loading. So you don’t have to wait for all the code to load to start hydrating.<br>React will start hydrating the comments after the code has finished loading. It is called <strong>Selective Hydration Process: </strong>when a heavy chunk of javascript doesn’t prevent the rest of the page from becoming interactive.</p><ul><li><strong>Problem 3: Hydrate for everything before you can interact with anything</strong></li></ul><p>When the hydration process starts, React doesn’t stop until it finishes the DOM tree.<br>Therefore, you must wait for all components to be hydrated before interacting with them.</p><p>For example, a comment widget has expensive rendering logic.<br>A device with low performance can crash the screen for a while. As a result, once hydration starts, the user cannot interact with any content until the entire tree is hydrated. For navigation, this is veeeery bad because the user may want to navigate out of a page, but since React is busy doing hydration, the user is kept on the current page that they don’t care about anymore.</p><p>This is because there is an order: <br><strong><em>fetch data -&gt; render to HTML -&gt; load code -&gt; hydrate</em></strong></p><p>Each step can start once the previous step has finished. The solution is to separate the work so that it is possible to do each stage for a part of the screen instead of the whole application.</p><p><strong>Solution</strong></p><p>Use the &lt;Suspense /&gt; in more places. It is possible to split how components are loaded.</p><p>For example, when the &lt;Suspense /&gt; is wrapped in the &lt;Comments /&gt; and the &lt;Sidebar /&gt;, their hydration no longer prevents the browser from doing another job.</p><pre>const Component = () =&gt; (<br>  &lt;&gt;<br>     &lt;Navbar /&gt;<br>     &lt;Suspense fallback={&lt;Spinner /&gt;}&gt;<br>       &lt;Sidebar /&gt;<br>     &lt;/Suspense&gt;<br>     &lt;Panel&gt;<br>       &lt;Post /&gt;<br>       &lt;Suspense fallback={&lt;Spinner /&gt;}&gt;<br>         &lt;Comments /&gt;<br>       &lt;/Suspense&gt;<br>     &lt;/Panel&gt;<br>  &lt;/&gt;<br>);</pre><p>Let me show you how this would work in SSR:</p><figure><img alt="The component has the following details in the order: Navbar (top of the page), Sidebar (right side of the page), Post (below the navbar), and Comments (below the post). 1- Navbar and Post loaded, but the Sidebar and Comments aren’t loaded. 2 — Navbar and Post loaded, post (below is not loaded; in other countries, take the Hydaration and hydrating in Sidebar. 3 — Navbar and Post loaded, post (below is not loaded; in other countries, take the Hydaration and hydrating in Sidebar." src="https://cdn-images-1.medium.com/max/684/1*DbkywPGECKUm7_IxaL3mxg.png" /><figcaption>Image of the steps of Suspense in SSR.</figcaption></figure><p>The HTML is loaded for all components, but the code still needs to be added.</p><ol><li>&lt;Navbar /&gt; and &lt;Post /&gt; are loaded code, but &lt;Sidebar /&gt; and &lt;Comments /&gt; components are not yet.</li><li>&lt;Sidebar /&gt; starts to hydrate because it is the first in the DOM tree.</li><li>But the user clicks in &lt;Comments /&gt; , when &lt;Sidebar /&gt; it is loading.</li><li>&lt;Comments /&gt; starts to hydrate instead &lt;Sidebar /&gt;.</li><li>Now, with the &lt;Comments /&gt; load, &lt;Sidebar /&gt; turn back to hydrate.</li><li>All components are loaded.</li></ol><p>The React starts hydrating everything early as possible and prioritizes the most urgent part of the screen based on user interaction.</p><h4>It’s time to say goodbye!</h4><p>In this article, I put together some information about how the new Suspense API works because we had a lot of behavioral differences, and now that it works in SSR, we can solve other problems.</p><p>I hope you enjoyed the content, and I will see you in the following article!</p><h4>References</h4><ul><li><a href="https://betterprogramming.pub/how-suspense-works-in-react-18-c7617a50447f">https://betterprogramming.pub/how-suspense-works-in-react-18-c7617a50447f</a></li><li><a href="https://blog.bitsrc.io/understanding-the-suspense-api-in-react-18-bbea3f6f6df1">https://blog.bitsrc.io/understanding-the-suspense-api-in-react-18-bbea3f6f6df1</a></li><li><a href="https://medium.com/rootcodelabs/using-react-18s-suspense-to-improve-code-quality-of-web-loaders-6fbb1dd5ab2a">https://medium.com/rootcodelabs/using-react-18s-suspense-to-improve-code-quality-of-web-loaders-6fbb1dd5ab2a</a></li><li><a href="https://github.com/reactjs/rfcs/blob/main/text/0213-suspense-in-react-18.md">https://github.com/reactjs/rfcs/blob/main/text/0213-suspense-in-react-18.md</a></li><li><a href="https://github.com/reactwg/react-18/discussions/37">https://github.com/reactwg/react-18/discussions/37</a></li><li><a href="https://medium.com/jspoint/introduction-to-react-v18-suspense-and-render-as-you-fetch-approach-1b259551a4c0">https://medium.com/jspoint/introduction-to-react-v18-suspense-and-render-as-you-fetch-approach-1b259551a4c0</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12360c6bfe02" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hurb-labs/the-new-suspense-api-in-react-18-12360c6bfe02">The new Suspense API in React 18</a> was originally published in <a href="https://medium.com/hurb-labs">hurb.labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to improve performance using memoization in React? [last pt]]]></title>
            <link>https://medium.com/hurb-labs/how-to-improve-performance-using-memoization-in-react-last-pt-dcf48039b4a4?source=rss-129e77291ab0------2</link>
            <guid isPermaLink="false">https://medium.com/p/dcf48039b4a4</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[memoization]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[usecallback]]></category>
            <category><![CDATA[usememo]]></category>
            <dc:creator><![CDATA[Ingryd Moura]]></dc:creator>
            <pubDate>Tue, 16 Aug 2022 13:10:41 GMT</pubDate>
            <atom:updated>2022-08-17T20:30:56.657Z</atom:updated>
            <content:encoded><![CDATA[<p><em>If you didn’t read the first part, </em><a href="https://medium.com/hurb-labs/how-to-improve-performance-using-memoization-in-react-pt-1-f7e18b83bb5a"><em>click here</em></a><em> and learn about the memo in React.</em></p><p>In this second part, I’ll talk about when and how to use <strong>useMemo </strong>and<strong> useCallback </strong>to enhance performance in your React application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*KOUi2_5dUw3-FhIucVhG-g.png" /><figcaption>useMemo and useCallback image.</figcaption></figure><h4>useMemo</h4><p>The useMemo is a React hook.</p><p>It is a function that returns a memoized value and has a dependencies array.</p><p><em>“So…How does useMemo help us?”</em></p><p><strong>It helps us memoize a value and resolve referential equality.</strong></p><p><em>“Hmmm…Referential equality?”</em></p><p>Yes, in Javascript, there are two equality comparison operators: == for abstract equality and === for strict equality (<strong>shallow compare</strong>). Referential equality uses strict equality comparison, which returns <em>true</em> if the operators are of the same type and value.</p><p>The <em>shallow compare</em> returns <em>true </em>if the values have the same reference<em>.</em></p><p>If you have primitive values like a number or string and the values are the same, return <em>true</em>. But, if you have an object, function, or array, it returns <em>false</em>.</p><p>Don’t worry if you don’t understand yet. Let’s go to the example:</p><ul><li>A simple application renders a fruit in the list by clicking the <em>“Add”</em> button<em>(Line 25 in without_useMemo.jsx)</em></li><li>The <em>count</em> function returns the number each time the number “2” appears in my list of fruits<em>(Line 13 in without_useMemo.jsx)</em>.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/89e01176b9823d07fc313ec2a0a51598/href">https://medium.com/media/89e01176b9823d07fc313ec2a0a51598/href</a></iframe><p>And my <em>Fruit</em> component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42ce5e06d15672fff1041c701c1324e3/href">https://medium.com/media/42ce5e06d15672fff1041c701c1324e3/href</a></iframe><p>So, we have a <em>count</em> function that doesn’t have <em>useMemo</em>.</p><p>When we create a calc or anything in the “body” of this component and React starts the render flow, all this code will be executed even if the result of these functions does not change.</p><p>Note that the component is being re-rendered every time a value is entered into the input.</p><p>You can see this from the blue border of the React dev tools extension, as seen below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/483/1*bgZ1gME8fkufvFfFUvMy_Q.gif" /><figcaption>Giphy of a user typing on input.</figcaption></figure><p>In other words, the whole thing is re-rendered and recalculated even if no information has been changed.</p><p>If the count function does a much more complex calculation, for example, taking 100000 items and performing some calculation with them, in these cases with useMemo, the calculation will not need to be performed unless any of the variables in the dependency array changes.</p><p>Now, with <em>useMemo(Line 16 in with_useMemo.jsx)</em>, my code looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b241f88cc1d7fe2455699b3c3c4822b6/href">https://medium.com/media/b241f88cc1d7fe2455699b3c3c4822b6/href</a></iframe><p>The console.log shows “<em>useMemo</em>” only once!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*FE6op6uglaA1iWIfYXbbGw.png" /><figcaption>Image showing useMemo one time on console.</figcaption></figure><p>But, If I add fruit, <em>useMemo</em> shows one more time because the <em>fruits</em> state in array dependency changed.</p><figure><img alt="In this giphy, I add two fruits in my application, and useMemo appears one when rendering the app and more two times in the console on the browser." src="https://cdn-images-1.medium.com/max/539/1*DRypVWuOrs-d54sD7lHCRQ.gif" /><figcaption>Giphy is showing useMemo when clicking on add button.</figcaption></figure><p>Go to the other example. Suppose I want to pass the <em>count</em> function to the <em>Fruit</em> component<em>(Line 30 in with_useMemo2.jsx)</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8bdd49a8ad2569f46beb1f1b22e0382/href">https://medium.com/media/d8bdd49a8ad2569f46beb1f1b22e0382/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5b903b5709285e77494b508bfc46f2b/href">https://medium.com/media/f5b903b5709285e77494b508bfc46f2b/href</a></iframe><p>In a <a href="https://medium.com/hurb-labs/how-to-improve-performance-using-memoization-in-react-pt-1-f7e18b83bb5a">previous post</a>, I explained <strong>Profiler</strong> from React Dev Tools, and we need to use it here.</p><p>So let’s start recording.</p><p>In this case, I’ll add other fruits, <em>useMemo</em> will appear as many times as the component <em>Fruit</em> was added, and in the <em>Profiler</em>, you will see that no fruit components are re-rendered.</p><figure><img alt="useMemo with primite value — In this giphy, I add two fruits in my application, and useMemo appears one when rendering the app and more two times in the console on the browser. When writing to the input, no useMemo console.log appears. Next, start recording in the React Dev Tools Profiler, add two more fruits and add one more letter to the input. With this, it will appear that no fruit components have been rendered in the Profiler." src="https://cdn-images-1.medium.com/max/781/1*O9-zqL0SPj1XNt4HEKJzsQ.gif" /><figcaption>Giphy shows useMemo with primitive value when clicking on the add button and the not rendered Fruit components.</figcaption></figure><p>According to the giphy above, this is happening because I am using <em>useMemo</em>, but even if I had not used <em>useMemo</em>, the components would not re-render.</p><p>That’s because the <em>count</em> function returns a primitive value (number, string)<em>(Line 16 in without_useMemo.jsx)</em>, so the memo’s comparison inside the <em>Fruit</em> component can verify that one is equal to the other.</p><p>When we have primitive values, the comparison of ===<strong><em> </em></strong>returns <em>true; </em>when it is an object, function, or array, it returns <em>false</em>.</p><p>So if the information I had in the <em>count</em> were not a number but an object<em>(Line 21 in with_useMemo2.jsx)</em>, the re-rendering would happen.</p><p>For example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8bdd49a8ad2569f46beb1f1b22e0382/href">https://medium.com/media/d8bdd49a8ad2569f46beb1f1b22e0382/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5b903b5709285e77494b508bfc46f2b/href">https://medium.com/media/f5b903b5709285e77494b508bfc46f2b/href</a></iframe><p>Because it has detected that the count property has changed, even though the count hasn’t changed. As React makes this <em>shallow compare,</em> it simply compares if the object reference is the same as the other, and in the case of javascript, this comparison doesn’t go into each of the object’s properties to see if the value has changed.</p><figure><img alt="useMemo with object value — In this giphy, I add three fruits in my application and write three letters on input. Next, start recording in the React Dev Tools Profiler, and all fruit components have been rendered in the Profiler." src="https://cdn-images-1.medium.com/max/781/1*CCv6_nJksVemyJJEeWFVrA.gif" /><figcaption>Giphy shows useMemo with object value when clicking on add button and the rendered Fruit components.</figcaption></figure><p><em>“I’ll use useMemo in my entire application.”</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/169/1*mgoaSI7irlyTnxslRXUxZw.gif" /><figcaption>Giphy of a cat shaking its head negatively</figcaption></figure><p>No guys!</p><p><strong>So…when should I use it?</strong></p><ul><li>Complex calculations</li><li>Solve referential equality problems</li></ul><h4>useCallback</h4><p>The useCallback is a React hook.</p><p>It is a function that returns a memoized callback and has a dependencies array.</p><p><em>“So…How does useCallback help us?”</em></p><p><strong>It helps us memoize a function and solve referential equality problems.</strong></p><p>Let’s go to the example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/28a0b276312162041948456e5f7681d1/href">https://medium.com/media/28a0b276312162041948456e5f7681d1/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42ce5e06d15672fff1041c701c1324e3/href">https://medium.com/media/42ce5e06d15672fff1041c701c1324e3/href</a></iframe><p>In this case, we have a favorite state fruit and a function that adds a new fruit to this list <em>(Line 14 in with_useCallback.jsx</em>). A prop passes this function to the <em>Fruit</em> component <em>(Line 36 in with_useCallback.jsx)</em>.</p><p>In the <em>Fruit</em> component, we have the prop <em>onAddFavoriteFruit</em> and a button to add the fruit to the favorites list.</p><p>We will add fruit to the application and write something in the input.<br>I start recording using the <em>Profiler</em>, add one more letter and stop recording.</p><figure><img alt="Without useCallback — In this giphy, three fruits are added in my application and three letters in my input. Next, start recording in the React Dev Tools Profiler and add one more letter on input, and all fruit components have been rendered." src="https://cdn-images-1.medium.com/max/839/1*dmInPpYPNbN2-8Rp-LSkvA.gif" /><figcaption>Giphy shows the example without useCallback when clicking on add button, adding letters on input, and all fruit components have been rendered.</figcaption></figure><p>Notice that all the fruit components have changed; they have entered the rendering flow because the <em>onAddFavoriteFruit</em> property has changed.</p><p>When a function is created within the <em>App</em> component, every time that component renders, that function will be recreated in memory, i.e., when I write to the input, that function is recreated and will occupy a new memory position.</p><p>When javascript compares whether one function is equal to another, it checks to see if both functions occupy the same memory position.</p><p>In this case, even when the memo in the <em>Fruit</em> component compares the previous props with the new property, it uses the <em>shallow compare</em> algorithm. It tries to check if this function is different from the previous one. <br>As this function occupies a different memory position than the previous one, and since it is being recreated every time the state is updated, it will understand that this component needs to render again. I mentioned <em>referential equality</em> when we check if a variable or function is equal to another based on its memory reference.</p><p>So to solve the problem, we add a <em>useCallback</em>(<em>Line 19 in with_useCallback.jsx)</em><strong> </strong>around the <em>addFavoriteFruit</em> function. The <em>useCallback</em> allows us to store a function in a memory location so that when that component renders, we don’t have to recreate that function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8822c25fe69338068dd55dfaf0d1a98/href">https://medium.com/media/d8822c25fe69338068dd55dfaf0d1a98/href</a></iframe><p>My <em>Fruit</em> component is the same.</p><p>Like <em>useMemo</em>, <em>useCallback</em> has an array of dependencies. In this case, for the <em>addFavoriteFruit</em> function, we add <em>favoriteFruit</em> as a dependency(<em>Line 27 in with_useCallback.jsx)</em>.</p><p>If we test now and add some fruit, save, write to the input and stop saving, you will see that none of the Fruit components are re-rendered.</p><figure><img alt="With useCallback — In this giphy, three fruits are added in my application and three letters in my input. Next, start recording in the React Dev Tools Profiler and add one more letter on input; all fruit components have not been rendered." src="https://cdn-images-1.medium.com/max/839/1*dRXyrQRtoFkT3Sj1IYBimg.gif" /><figcaption>Giphy shows the example with useCallback when clicking on add button, adding input values, all fruit components have not been rendered.</figcaption></figure><p><strong>When should I use it?</strong></p><ul><li>Solve referential equality problems.</li></ul><p>The <em>useCallback</em> is <strong>not</strong> a hook to be used when a function has a lot of code inside; it will <strong>not</strong> make a function load faster; it will only prevent that function from being recreated each time it is rendered.</p><p><em>“So can I use useCallback for everything?”<br>- </em>As I said to the others above, <strong>Nooop</strong>! 😬</p><p>When a function is accessed only by the component that creates it; in most cases, useCallback will be more expensive than React by recreating that function each time it is rendered. For example, a simple function used only by that component itself, without being passed to another child component, or a function that is not within a context.</p><p>So only use useCallback if the function is being passed to other components or is a function in a context where more than one component accesses the same function.</p><p>I hope you understand how and when to use <strong>useMemo</strong> and <strong>useCallback</strong> React hooks in your applications and improve the performance of your projects!</p><h4>See you later!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*HFH4S8Ekt-1Rn5YW3IkpZw.gif" /><figcaption>Giphy of a cat going away.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dcf48039b4a4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hurb-labs/how-to-improve-performance-using-memoization-in-react-last-pt-dcf48039b4a4">How to improve performance using memoization in React? [last pt]</a> was originally published in <a href="https://medium.com/hurb-labs">hurb.labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to improve performance using memoization in React? [pt.1]]]></title>
            <link>https://medium.com/hurb-labs/how-to-improve-performance-using-memoization-in-react-pt-1-f7e18b83bb5a?source=rss-129e77291ab0------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7e18b83bb5a</guid>
            <category><![CDATA[react-memo]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[memoization]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Ingryd Moura]]></dc:creator>
            <pubDate>Fri, 03 Jun 2022 13:44:27 GMT</pubDate>
            <atom:updated>2022-08-19T20:30:49.666Z</atom:updated>
            <content:encoded><![CDATA[<p>In this first part, I’ll talk about when and how to use <strong>memo</strong> to improve performance in your React application. In the other parts, I will talk about how to use and what the <strong>useMemo</strong> and <strong>useCallback</strong> are for.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*jEfgHlJqwTin_CAs0iGy3g.png" /><figcaption>React.memo() image</figcaption></figure><p>This article is divided as follows:</p><ul><li>Diffing Algorithm</li><li>Profiler</li><li>memo</li></ul><p>I know you must be saying to yourself: <br>- <em>“If I use all of them in my application, it would be wonderful!”</em></p><p>Me:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*84PFTh4GMsyrPdar77CvKw.gif" /><figcaption>Crying baby giphy</figcaption></figure><p>Just stop thinking about this, please! Let’s take it easy! 🙌</p><p>First, let’s understand what’s is the <a href="https://reactjs.org/docs/reconciliation.html#the-diffing-algorithm"><strong>React Diffing Algorithm</strong></a>.</p><h3><strong>Diffing Algorithm</strong></h3><p>It is the component rendering process! This process compares the new HTML with the older HTML if it exists.</p><p>This process has a few steps:</p><ul><li>The component creates its HTML;</li><li>Check if there is a change in the HTML created to this previous HTML (only if it’s not the first time it’s being rendered);</li><li>Perform the diffing algorithm to apply those changes.</li></ul><p>For example, when a component has any changes, such as a state changed or made a change in a child component, this component re-renders; that is, the entire <strong>DOM</strong> has generated again, but this is not done directly in the HTML that we users see but in the <strong>VirtualDOM</strong>.</p><p>❗️<strong>An important information:</strong> React doesn’t remove all content because of one change; it just replaces what was changed.</p><pre>&lt;Container <strong>className=&quot;container&quot;</strong> title=&quot;Container1&quot;&gt;Container1&lt;/Container&gt;</pre><pre>&lt;Container <strong>className=&quot;wrapper&quot;</strong> title=&quot;Container1&quot;&gt;Container1&lt;/Container&gt;</pre><p>In the example above, React doesn’t remove <em>Container</em>, <em>title,</em> or your <em>children,</em> it<em> </em>just replaces the <em>className</em>.</p><h3>Profiler</h3><p>So, before we get to the most important matter, I need to explain <a href="https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi"><strong>React Developer Tools</strong></a>, a browser extension that you need to install to make it work. Then, we’ll use the <strong>Profiler</strong> to find out how the memo works in your application.</p><p>And here is the Profiler! 🎉</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aCA-9X4yJKUF8xT2hKtunQ.png" /><figcaption>Profiler home screen image</figcaption></figure><p>The Profiler works by recording specific actions. You can do this by clicking the circle button shown in the picture below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*rG889R7l_taNNvqBRF_D0g.png" /><figcaption>Image of the mouse cursor on “start profiling”</figcaption></figure><p>And it has two types of visualization:</p><ul><li><strong>Flamegraph chart:</strong> Sort by rendering order. Each bar in the graph represents a React component, and the width of each bar represents how long it took to render the component and its children.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PJ-WQIWE78ukECtPz5W0Sg.png" /><figcaption>Flamegraph chart image</figcaption></figure><ul><li><strong>Ranked chart:</strong> Sort by render time. Displays each component in the commit as a bar, but this time they are ordered by the duration of their render.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ftd-8bug503Ml8w39Ma8ng.png" /><figcaption>Ranked chart image</figcaption></figure><p>And these colored rectangles represent each rendering that took place in the application. We’ll see more about this later!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*0fH6X20xe7qfK_MZ73TTeQ.png" /><figcaption>Image of colored rectangles representing each render</figcaption></figure><p>There are more details about Profiler, but I don’t want to make this article tooooo boring, so I’ll explain a few things along this journey.</p><p>No more blah blah blah!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*iE4ZTwEhZuBeSa1zeHbgmA.gif" /><figcaption>Blah blah blah image</figcaption></figure><p>Finally…</p><h3>Memo</h3><p>React.memo is a HOC (Higher-Order Component).</p><p><em>“Wait…What?!”</em><br>A higher-order component is a function that receives a component and returns a new component.</p><p><em>“So…How does memo help us?”</em></p><p><strong>It prevents all child components from rendering because of the parent render.</strong></p><p><em>“I still don’t understand… what do you mean?”</em></p><p>For example, a simple application renders a fruit in the list by clicking the “Add” button:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/54e1f0c4a3b63676e5e904436bce3c0e/href">https://medium.com/media/54e1f0c4a3b63676e5e904436bce3c0e/href</a></iframe><p>And this is a Fruit component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43c800609b9868d3708b6fb924a57363/href">https://medium.com/media/43c800609b9868d3708b6fb924a57363/href</a></iframe><p><em>In Profiler do as follows: “Start profiling” -&gt; Add fruits in your application -&gt; “Stop profiling”</em></p><p>So…you see this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bu8qwRABzfhaNCEZLfLUEQ.png" /><figcaption>Image with App and Fruit components rendered</figcaption></figure><p>Note that the Fruit components are colored, which means, they have been rendered. They were rendered because the App component was rendered.</p><p><strong>The memo will help us solve this problem! </strong>🙏</p><p>The memo will say the following to that component “Heeey, when your parent component renders BEFORE entering the render flow, I want you to compare the properties of that component, and if no information has changed, I want you to not even enter that render flow.”</p><p>Let’s go add a memo in the Fruit component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42ce5e06d15672fff1041c701c1324e3/href">https://medium.com/media/42ce5e06d15672fff1041c701c1324e3/href</a></iframe><p>Now, if you test this in your Profiler again…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/185/1*NhqYbjxKWiU0fSxm9ifrjg.gif" /><figcaption>Giphy of surprised cat</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LaYQA74tpZKJ1qRQ0ZwZeQ.png" /><figcaption>Image with Fruit 0 component not rendered</figcaption></figure><p>Note that the “Fruit 0&quot; component didn’t render!</p><p>The colored Fruit component, on the other hand, has been rendered because this second commit is the first time it has been rendered.</p><p>Let’s check how it goes when we add 3 fruits:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zGM4ZIn0vgcPKlDTrvWrdQ.png" /><figcaption>Image with Fruit 0 and Fruit 1 components not rendered</figcaption></figure><p>In this case, It’s added the “Fruit 0” (gray), “Fruit 1” (gray), and “Fruit 2” (green). “Fruit 0” and “Fruit 1&quot; was added in the first and second render. The third and last commit is colored because it was the first time that “Fruit 2” was rendered.</p><p>React.memo also accepts an optional second parameter to create a custom comparison.</p><p>For example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/00703a93e2f4eb2fa3705806a95f0d60/href">https://medium.com/media/00703a93e2f4eb2fa3705806a95f0d60/href</a></iframe><p>propsAreEqual() function returns true if prev and next props are equal.</p><p>The same assertion was made at the beginning:</p><p><em>“I’ll use it on everything then!</em>😍”</p><p>NO NO NO NO NOOOO!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*jYM06KPyPZej9lU6g8dX8Q.gif" /><figcaption>“NOOOO!” giphy</figcaption></figure><p>The memo<strong> </strong>works like this:</p><p>It needs to compare! It needs to go through the properties of the component and compare whether they are the same as before, and then allow it to enter or not the render flow.</p><p>Suppose the memo has properties to compare. In that case, this may be slower than creating a new version of this component and letting React’s reconciliation algorithm do what it already does in some cases.</p><p>So it’s not worth using memo on all components because this property calculation can be slower than letting the React reconciliation algorithm run.</p><p><strong>So...when should I use it?</strong></p><ul><li><strong>Medium to large components:</strong> this example I used is quite simple, but in the case of an application with a much larger component, with a lot of functionality and which shows a lot of things on the screen it would be good to use memo.</li><li><strong>Re-renders with the same props:</strong> when a component renders several times and always with the same properties.</li><li><strong>Complex Pure Functional Components: </strong>this means that given the properties that I pass to the component, the return will always be the same. It’s not a pure component if you use external resources of this component to make it work; for example, a component that makes a comparison with some date gets the current date and makes a countdown. This current date is happening in the users&#39; environment; it is not something that comes from the properties.</li></ul><p>This is the first part of the article; I hope I helped you with the questions: what is, how, and when to use memo.</p><p>In the <a href="https://medium.com/hurb-labs/how-to-improve-performance-using-memoization-in-react-last-pt-dcf48039b4a4">following articles</a>, I will talk about <strong>useMemo</strong> and <strong>useCallback</strong>, showing examples and how to use them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*326g7kcrJ4xBKEOBMz7uxw.gif" /><figcaption>Giphy of a waving cat</figcaption></figure><h3>See you later!</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7e18b83bb5a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hurb-labs/how-to-improve-performance-using-memoization-in-react-pt-1-f7e18b83bb5a">How to improve performance using memoization in React? [pt.1]</a> was originally published in <a href="https://medium.com/hurb-labs">hurb.labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A importância de fazer testes]]></title>
            <link>https://medium.com/hurb-labs/a-import%C3%A2ncia-de-fazer-testes-96b794ab7d5e?source=rss-129e77291ab0------2</link>
            <guid isPermaLink="false">https://medium.com/p/96b794ab7d5e</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[testes-de-software]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[tdd]]></category>
            <dc:creator><![CDATA[Ingryd Moura]]></dc:creator>
            <pubDate>Mon, 07 Feb 2022 20:45:41 GMT</pubDate>
            <atom:updated>2022-02-07T20:45:41.749Z</atom:updated>
            <content:encoded><![CDATA[<p>Para chegarmos em um raciocínio em comum, vou contar uma história que é a realidade de muitas empresas.</p><p>Um time passou mais de 2 meses idealizando um projeto de loja virtual, foram feitos os levantamentos de requisitos, arquitetura e desenvolvimento da aplicação. Porém, durante o processo de desenvolvimento o prazo para a entrega do produto estava próximo e na pressa de subir a aplicação para produção, os testes ficaram de fora do backlog.</p><p>Após uma semana do produto em produção…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*MLwoQKDUV0jXpST7Oa22jA.gif" /><figcaption>Gif de um barril explodindo.</figcaption></figure><p>Chega o primeiro bug.</p><p>E quando isso acontecer a última coisa que os desenvolvedores vão pensar é em fazer testes.</p><p>Isso pode acabar ocorrendo diversas vezes, novas features também serão criadas e novos problemas aparecerão e o tempo que vai levar para resolvê-los irá crescer exponencialmente conforme a aplicação se torna mais robusta. Vai chegar um momento que os desenvolvedores vão olhar pra aplicação e ficar assim:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*ABW-9KwHX90KAsX0PXt5SA.gif" /><figcaption>Gif de uma pessoa confusa.</figcaption></figure><p>Já pensou na energia que seu time gastou pra resolver bugs poderia ter sido utilizada pra criação de novas features se tivessem priorizado os testes ?</p><p>É claro que existem prazos para serem cumpridos e metas a serem alcançadas, porém nós, desenvolvedores, sabemos que a saúde da nossa aplicação nos afeta diretamente. Então sempre que possível priorize os testes, consequentemente irá priorizar a performance e sanidade do time que trabalha com você e aqueles que podem chegar de paraquedas no projeto.</p><p>Depois de toda essa história, você deve estar se perguntando: <em>“Mas por onde começo?”</em></p><p>Como estamos falando sobre um primeiro passo para começar a fazer testes, o foco será em testes unitários, pois são os mais rápidos e baratos de serem implementados.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*eAF5cu1lI9umoNgURlRVKQ.png" /><figcaption>Imagem de uma pirâmide ordenando testes e2e, integração e unitários de acordo com velocidade e custo.</figcaption></figure><p>Esta imagem, inclusive, foi retirada de um artigo do Kent C. Dodds, que possui um conteúdo bem interessante para o tema que estou tratando aqui, caso tenha interesse em saber mais é só acessar o <a href="https://kentcdodds.com/blog/write-tests">post</a>.</p><p>Primeiro de tudo, escolha o framework que irá utilizar para fazer os testes (jest, mocha, jasmine ou outro). Existem muitos artigos que mostram as diferenças entre esses 3 principais, não vou detalhá-los aqui mas você pode saber mais neste <a href="https://www.lambdatest.com/blog/jest-vs-mocha-vs-jasmine/">artigo</a>.</p><p>Se você está no começo da sua aplicação ou ainda na etapa de prototipação, priorize os testes juntamente da implementação dos seus componentes. A cada componente implementado crie o respectivo teste, assim você evitará diversos componentes sem teste a longo prazo e bugs inesperados.</p><p>Caso você já tenha um projeto robusto e ainda não criou os testes, pense que <em>“Antes tarde do que nunca”. </em>Você pode começar a testar os componentes internos para os mais externos ou dos mais externos para os internos ou priorizar os testes das partes mais críticas da aplicaçã para as menos críticas. Fica a critério do time esta decisão, porém tenha em mente de que se os testes começarem a ficar complexos de serem implementados é um sinal de alerta para uma possível refatoração do código. Lembra sobre o que eu disse da saúde da aplicação? Pois é. Nesse caso o time terá que organizar um tempo no backlog para refatorar o código para poder avançar nos testes.</p><p>Coloque como uma meta do seu time alcançar x% de cobertura de testes em um determinado tempo. Visando sempre aumentar esse percentual. Você pode usar o coverage para ter uma análise mais detalhada dos testes e o que poderia melhorar e ser testado.</p><p>O coverage é uma análise da cobertura de testes que seu projeto possui. É possível visualizar em detalhes através de um html que é gerado nesse processo sobre o que é preciso melhorar nos seus testes para ter mais cenários cobertos e consequentemente aumentar o % no seu coverage. Um outro ponto importante é o threshold, que possibilita que você coloque alguns valores mínimos para cada opção do coverage, caso aquele valor esteja menor do que o configurado é informado um erro ao rodar os testes. Explico melhor logo abaixo como utilizar isso a favor do time. Neste <a href="https://www.valentinog.com/blog/jest-coverage/">artigo</a> possui um setup do jest para utilizar coverage e threshold.</p><p>Lembrando que ter 100% de cobertura de testes não significa que sua aplicação está 100% testada. Fique atento a falsos positivos e a maneira como os testes estão sendo feitos.</p><p>Uma outra forma de ter segurança a respeito da evolução dos testes, é criar através do CI do GitHub ou Gitlab uma etapa para validação do coverage dos seus testes. Basta configurar o threshold que falei anteriormente com um determinado valor percentual no seu projeto e se este valor for menor, o CI irá falhar. Isso impede que o percentual de testes no projeto diminua e é uma maneira de criar comprometimento do time com a criação de testes para a aplicação.</p><h4>Resumindo as dicas:</h4><ul><li>Faça testes e priorize a saúde da aplicação.</li><li>Faça testes e seu time estará mais seguro de determinados cenários da aplicação.</li><li>Faça testes e evite efeitos surpresinha.</li><li>Faça testes e evolua-os.</li><li>Faça testes e tenha um time mais feliz.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*Z7Kk7-B2VE5MNJfbgFVHFQ.gif" /><figcaption>Gif motivacional</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96b794ab7d5e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hurb-labs/a-import%C3%A2ncia-de-fazer-testes-96b794ab7d5e">A importância de fazer testes</a> was originally published in <a href="https://medium.com/hurb-labs">hurb.labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Um pouco sobre GitHub Actions]]></title>
            <link>https://medium.com/hurb-labs/um-pouco-sobre-github-actions-fe6ab77998ca?source=rss-129e77291ab0------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe6ab77998ca</guid>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[continuous-integration]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[continuous-delivery]]></category>
            <dc:creator><![CDATA[Ingryd Moura]]></dc:creator>
            <pubDate>Tue, 24 Aug 2021 21:59:13 GMT</pubDate>
            <atom:updated>2021-08-24T21:59:13.953Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*YcFmahlLvOPyjfNtw1GkbQ.png" /></figure><p>Como o próprio título deste artigo propõe, irei falar um pouco sobre alguns conceitos e pontos de atenção na utilização do GitHub Actions durante o seu processo de automatização dos fluxos de trabalho.</p><h4>Tá… mas o que é esse tal de GitHub Actions ?</h4><p>É uma plataforma de CI/CD (<em>Continuous Integration</em> e <em>Continuous Delivery</em>) do GitHub, ou seja, vai te ajudar nos processos para tornar o desenvolvimento, teste e entrega de “peças” de software de forma mais rápida e eficiente.</p><h4>Agora vamos ao que interessa…</h4><p>Quando temos um repositório no GitHub, qualquer usuário que tenha acesso poderá enviar um push, pull e etc. Essas ações podem ser usadas para iniciar o que chamamos de <strong>workflow</strong> no GitHub Actions.</p><p>Um <strong>workflow</strong> é um conjunto de tarefas a serem executadas simultaneamente ou sequencialmente. Ele possui um <strong>job</strong>, podendo existir mais de um. E estes jobs possuem <strong>steps</strong>. E estes steps possuem <strong>actions</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*qH_i8Pa5_ba_PB1TW3jb8Q.png" /></figure><p>No exemplo acima temos um <em>workflow</em> que será acionado em um evento de <em>push</em>. Ele possui dois <em>jobs</em> e em cada job possui as <em>steps. </em>Essas<em> steps </em>estão divididas em duas com uma <em>action</em> em cada.</p><p>Explicando de forma mais detalhada <em>(mas fique de boas que você verá exemplos sobre cada um)</em>:</p><ul><li><strong>Workflow<br></strong>O workflow tem um campo <em>name</em>, ele não é obrigatório, mas é legal incluir um nome referente ao fluxo que você está criando. Caso você não coloque ele vai definir seu <em>name</em> como o caminho do seu workflow relativo a raiz do seu repositório.</li></ul><pre>name: My First Workflow</pre><ul><li><strong>on<br></strong>É obrigatório e é onde colocamos os eventos que farão aquele workflow rodar, pode ser um único evento ou um array de eventos. Você também consegue especificar a branch para qual cada evento irá rodar.</li></ul><pre>on: [push, pull_request]</pre><pre>--------------------------------------------------------------------</pre><pre>on: <br>  push:<br>    branches:<br>      - main<br>  pull_request:<br>    branches:<br>      - main</pre><ul><li><strong>Job</strong><br>Como mencionei anteriormente um workflow pode ter um ou mais <em>jobs,</em> podendo ser executados em paralelo (por padrão) ou sequencialmente utilizando o parâmetro <em>needs.<br></em>Cada job é executado obrigatoriamente por um runner (hospedado pelo GitHub ou auto-hospedado), basta você adicionar <em>runs-on.</em></li></ul><pre>jobs:<br>  my-first-job:<br>    name: My First Job<br>    runs-on: ubuntu-latest</pre><pre>--------------------------------------------------------------------</pre><pre>jobs:<br>  my-first-job:<br>    name: My First Job<br>    runs-on: ubuntu-latest</pre><pre>my-second-job:<br>    name: My Second Job<br>    runs-on: ubuntu-latest<br>    needs: my-first-job</pre><ul><li><strong>Steps<br></strong>Um <em>job</em> pode conter uma <em>step</em> ou uma sequência de <em>steps. </em>As <em>steps</em> podem executar comandos, configurações e <em>actions</em>. <br>Nem todas as <em>steps</em> executam <em>actions</em>, mas todas as <em>actions</em> são executadas dentro de uma <em>step.</em></li></ul><p>No exemplo abaixo há duas <em>steps</em>, na primeira ocorre a <em>action</em> de checkout e na segunda utilizando ENVs irá informar uma mensagem ‘Hello World’.</p><pre>jobs:<br>  my-first-job:<br>    name: My First Job<br>    runs-on: ubuntu-latest<br>    steps:<br>      - name: checkout repo<br>        uses: actions/checkout@v2 <br>      - name: print Hello, World<br>        env:  <br>          VAR1: Hello, <br>          VAR2: World!<br>        run: echo $VAR1 $VAR2</pre><p>Você também pode usar um <em>if </em>para executar uma <em>step</em> de acordo com aquela condição. <br>Neste exemplo a <em>step</em> é executada apenas quando o tipo do evento é um <em>pull_request</em>.</p><pre>steps:<br>  - name: My First Step<br>    if: ${{ github.event_name == &#39;pull_request&#39; }}<br>    run: echo event is a pull request</pre><ul><li><strong>Actions<br></strong> Vimos agora há pouco sobre as <em>steps</em> e que elas possuem o método <em>uses. </em>Esse método que você vai utilizar para setar suas <em>actions.<br></em>É super recomendado que você inclua as versões das <em>actions</em>. Isso porque quando o proprietário de uma dessas <em>actions</em> publicar uma atualização pode acabar interrompendo seu workflow ou causar algum comportamento ‘surpresinha’.</li></ul><p>No exemplo abaixo é uma <em>action</em> com controle de versão.</p><pre>steps:<br>  - name: Step with specific version<br>    uses: actions/checkout@v2.0</pre><p>Após fazer uma breve explicação desses conceitos mais básicos e como utilizá-los, acho mega útil você saber sobre dois pontos legais do GitHub Actions:</p><p><strong>Cache e artifacts</strong>!</p><p>Diferente dos <em>steps</em>, cada <em>job</em> é executado em uma nova instância do runner, logo, eles não conseguem compartilhar dados entre si.</p><p>Ai que entra o <em>cache</em> e <em>artifacts</em> em ação!</p><p>Os <strong>artifacts</strong> permitem que você compartilhe os dados entre os <em>jobs</em> de um workflow através de download/upload e salva os arquivos quando o workflow é concluído. Normalmente, os <em>artifacts</em> mais comuns são arquivos de log, resultados de teste, screenshots, coverage, resultados de desempenho de teste e entre outros. <br>Por padrão, o GitHub armazena os <em>artifacts</em> por 90 dias mas é possível personalizar esse tempo.<br>Outro ponto importante é os <em>artifacts</em> utilizam espaço de armazenamento no GitHub, então cuidado com o tamanho dos arquivos que você está dispondo pra download/upload.</p><p>Abaixo é um exemplo de upload de um <em>artifact</em> de coverage.</p><pre>jobs:<br>  my-artifacts-job:<br>    name: My Artifacts Job<br>    runs-on: ubuntu-latest<br>    steps:<br>     - name: Archive code coverage results<br>       uses: actions/upload-artifact@v2<br>       with:<br>        name: code-coverage-report<br>        path: output/test/code-coverage.html</pre><p>O <strong>cache</strong> é usado para reutilização de dados/arquivos que não mudam com tanta frequência entre os <em>jobs</em> ou <em>workflows</em>. Normalmente utilizado em ferramentas de gerenciamento de pacotes como o npm, yarn e outros.<br>A ação de cache tenta restaurar um cache de acordo com a key fornecida. Quando a ação encontra o cache, restaura os arquivos em cache pro path configurado, se não existir uma key, é criado uma nova entrada se o <em>job</em> for executado com sucesso.<br>Uma vez que o cache é criado, ele fica disponível para todos os workflows no mesmo repositório.</p><p>Neste caso é um exemplo de <em>job</em> com um cache do <em>node_modules</em>, onde a key do seu cache é <em>npm-deps-${{ hashFiles(‘**/package-lock.json’) }} </em>e que pode ser utilizada em outros jobs para condicionais. A <em>restore-keys</em> é utilizada quando ocorre a perda de cache, então a action procura por caches alternativos que correspondam a <em>npm-deps- .</em></p><pre>jobs:<br>  my-cache-job:<br>    name: My Cache Job<br>    runs-on: ubuntu-latest<br>    steps:<br>      - name: cache node modules<br>        uses: actions/cache@v2<br>        with:<br>         path: ~/.npm<br>         key: npm-deps-${{ hashFiles(&#39;**/package-lock.json&#39;) }}<br>         restore-keys: npm-deps-</pre><p><strong>Agora que você já está mais por dentro do assunto, irei colocar aqui alguns pontos importantes:</strong></p><ul><li>No seu projeto poderá existir mais de um workflow, porém todos deverão estar em uma pasta <em>.github/workflows.</em></li><li>Separamos em mais de um workflow quando precisamos definir configurações diferentes nos <em>steps/jobs</em> a partir de um evento (push, pull request, etc). Você pode querer fazer determinado <em>job/step</em> pro seu evento de push mas outras configurações pro seu evento de pull request, por exemplo.</li><li>Mantenha as suas actions mais leves possíveis, pois quanto mais tempo ela levar pra ser configurada e executada, mais tempo você vai gastar esperando. Lembre-se que existe um limite de tempo para o plano gratuito que suporta até 2000 minutos.</li><li>Relacionado ao ponto exatamente acima deste, não instale depêndencias desnecessariamente. Você pode utilizar o mecanismo de cache pra te auxiliar nisso.</li><li>Não code os secrets! Você consegue pela plataforma do GitHub configurá-los no seu repositório e fornecer como entradas ou variáveis de ambiente.</li></ul><p><strong><em>Fica aqui o meu “até logo”.</em></strong></p><p>Espero ter clareado <em>“um pouco”</em> sobre as funcionalidades e opções que o GitHub Actions proporciona no âmbito de desenvolvimento de software. Há <strong>MUITO</strong> além do que mencionei aqui, existem diversas funcionalidades e opções diferentes de novas <em>actions</em> que a todo momento são implementadas. Vale dar um olhada na <a href="https://docs.github.com/en/actions">documentação oficial</a>, ela é bem ampla mas acredito que com o que você leu aqui não ficará tão perdido.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe6ab77998ca" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hurb-labs/um-pouco-sobre-github-actions-fe6ab77998ca">Um pouco sobre GitHub Actions</a> was originally published in <a href="https://medium.com/hurb-labs">hurb.labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>