<?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 Alvaro Losada on Medium]]></title>
        <description><![CDATA[Stories by Alvaro Losada on Medium]]></description>
        <link>https://medium.com/@alvarolosada?source=rss-8d07b8433061------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Kxy8oqyGXyBMJil05-QbyQ@2x.jpeg</url>
            <title>Stories by Alvaro Losada on Medium</title>
            <link>https://medium.com/@alvarolosada?source=rss-8d07b8433061------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 25 Nov 2026 02:25:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alvarolosada/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[Tracing the Lifecycle: From Developer’s Editor to JS Virtual Machine Execution]]></title>
            <link>https://medium.com/@alvarolosada/tracing-the-lifecycle-from-developers-editor-to-js-virtual-machine-execution-7e1ba9c4eeae?source=rss-8d07b8433061------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e1ba9c4eeae</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Alvaro Losada]]></dc:creator>
            <pubDate>Wed, 29 Nov 2023 17:06:47 GMT</pubDate>
            <atom:updated>2023-12-21T14:53:35.024Z</atom:updated>
            <content:encoded><![CDATA[<p>A walk through the process of a program since it leaves a developer’s editor until it is executed by the JS VM</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2S2qfvjpbOLHhcpq9_b92w.jpeg" /></figure><p>Let’s dive in!</p><p>I’ve divided the process in four different phases.</p><ol><li>After a program leaves a developer’s editor, it gets transpiled by Babel, then packed by Webpack (and perhaps half a dozen other build processes), then it gets delivered in that very different form to a JS engine.</li><li>The JS engine parses the code to an AST.</li><li>Then the engine converts that AST to a kind-of byte code, a binary intermediate representation (IR), which is then refined/converted even further by the optimizing JIT compiler.</li><li>Finally, the JS VM executes the program.</li></ol><h3>Transpiration and bundling</h3><p>Let’s consider a simple example involving a modern JavaScript feature, such as using arrow functions. The original code might look like this:</p><pre>const add = (a, b) =&gt; a + b;<br>console.log(add(3, 7));</pre><ol><li><strong>Developer’s Editor:</strong> The developer writes the code in a modern JavaScript editor.</li><li><strong>Babel Transpilation:</strong> Babel is used to transpile the code, converting modern JavaScript (ES6+) to a more widely supported version. After transpilation, the code might look like this:</li></ol><pre>// Transpiled code by Babel<br>&quot;use strict&quot;;</pre><pre>var add = function add(a, b) {<br>  return a + b;<br>};</pre><pre>console.log(add(3, 7));</pre><ol><li><strong>Webpack Packing:</strong> Webpack is employed to bundle and pack the code along with its dependencies. The packed code might be a single file with minimized and optimized code:</li></ol><pre>// Packed code by Webpack<br>!function(){&quot;use strict&quot;;var n=function(n,e){return n+e};console.log(n(3,7))}();</pre><ol><li><strong>Delivery to JS Engine:</strong> The packed code, along with any other assets, is then delivered to the JavaScript engine (like V8 in Chrome or SpiderMonkey in Firefox) for execution in the browser environment.</li></ol><p>This process ensures that the original developer-written code is transformed and optimized to be compatible with a wide range of browsers and JavaScript engines.</p><h3>Code parsing to an AST</h3><p>When the packed code reaches the JavaScript engine, it undergoes parsing, during which it is converted into an Abstract Syntax Tree (AST). Here’s a simplified explanation of the process:</p><ol><li><strong>Lexical Analysis:</strong> The code is first broken down into tokens by the lexer. Tokens are the smallest units of the code, such as keywords, identifiers, operators, etc. In our example, tokens would include “var,” “add,” “function,” “(“, “)”, “{,” etc.</li><li><strong>Syntax Parsing:</strong> The parser then takes these tokens and organizes them into a hierarchical structure, creating the AST. This structure represents the syntactic relationships between different parts of the code. For our example, the AST might have nodes for variable declaration, function expression, and the function call.</li><li><strong>AST Representation:</strong> The AST is a tree-like structure where each node corresponds to a syntactic element, and the relationships between nodes represent the code’s structure. For instance:</li></ol><pre>Program<br> └── ExpressionStatement<br>     └── CallExpression<br>         ├── Identifier (console)<br>         └── Identifier (add)<br>         └── Literal (3)<br>         └── Literal (7)</pre><ol><li>This hypothetical AST represents the <strong>console.log(add(3, 7));</strong> statement.</li><li><strong>Execution:</strong> Once the AST is constructed, the engine traverses it to execute the code. In the process, it may optimize and generate machine code for better performance.</li></ol><p>In summary, the JavaScript engine parses the packed code into an AST, providing a structured representation of the code’s syntax. This AST is then used for further analysis and execution by the engine.</p><h3>Optimization</h3><p>After the JavaScript engine constructs the Abstract Syntax Tree (AST), it proceeds to convert it into a binary intermediate representation (IR). This IR serves as a more compact and machine-friendly representation of the code. Here’s how the process typically unfolds:</p><ol><li><strong>Intermediate Representation (IR):</strong> The AST is transformed into an intermediate representation, which is a low-level, platform-independent representation of the code. This step makes it easier for subsequent processes, like optimization and execution, to work with the code. The IR is a form of bytecode, although it might not be stored on disk like traditional bytecode.</li><li><strong>Optimizing JIT Compilation:</strong> The engine uses a Just-In-Time (JIT) compiler to further optimize the intermediate representation. The JIT compiler analyzes the code’s execution patterns during runtime and applies various optimizations to improve performance. This could involve inlining functions, eliminating dead code, and reordering instructions for better execution speed.</li><li><strong>Final Machine Code:</strong> The optimized intermediate representation is then translated into machine code specific to the underlying hardware architecture. This machine code is what actually gets executed by the processor. The JIT compilation occurs dynamically at runtime, adapting to the execution characteristics of the code.</li></ol><p>In essence, the JavaScript engine first converts the AST into an intermediate representation, which is then refined and optimized by the JIT compiler before being translated into machine code for efficient execution. This dynamic and adaptive compilation process is one of the reasons JavaScript can achieve good performance in modern web browsers.</p><h3>Execution</h3><p>After the JavaScript engine completes the processes of parsing the code into an Abstract Syntax Tree (AST), converting the AST to a binary intermediate representation (IR), and optimizing it with a Just-In-Time (JIT) compiler, the final step involves the execution of the program.</p><ol><li><strong>Execution of Machine Code:</strong> The optimized machine code, generated by the JIT compiler, is executed by the JavaScript Virtual Machine (VM). This machine code is a set of instructions that the computer’s processor understands and can execute directly.</li><li><strong>Runtime Environment:</strong> During execution, the JavaScript VM provides a runtime environment for the program. This includes managing memory, handling variables, and interacting with the browser’s Document Object Model (DOM) if the code is running in a browser environment.</li><li><strong>Interpretation and Compilation:</strong> The JavaScript VM uses a combination of interpretation and compilation. Initially, the code might be interpreted for quick startup, but as the program runs, the JIT compiler identifies hot paths (frequently executed portions) and compiles them to highly optimized machine code for better performance.</li><li><strong>Dynamic Typing:</strong> JavaScript is a dynamically-typed language, which means variable types are determined at runtime. The VM handles the dynamic nature of the language, adjusting to changes in variable types during execution.</li></ol><p>In summary, the JavaScript Virtual Machine executes the optimized machine code, facilitating the dynamic and efficient execution of the program. The combination of parsing, intermediate representation, JIT compilation, and execution creates a runtime environment where modern JavaScript applications can run with good performance in web browsers or other environments that host JavaScript engines.</p><h3>Sum up</h3><p>In this blog we’ve walked through the whole process involved in compiling and executing a basic JavaScript program.</p><p>As the program expands, the introduction of new dependencies, the user experience, the scalability or the code optimizations prompts considerations for enhancing efficiency. Techniques such as code splitting and tree shaking become increasingly important to ensure optimal code performance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e1ba9c4eeae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Javascript executes under the hood]]></title>
            <link>https://medium.com/@alvarolosada/javascript-under-the-hood-580e4ba0337c?source=rss-8d07b8433061------2</link>
            <guid isPermaLink="false">https://medium.com/p/580e4ba0337c</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[language]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <dc:creator><![CDATA[Alvaro Losada]]></dc:creator>
            <pubDate>Sat, 25 Nov 2023 10:28:13 GMT</pubDate>
            <atom:updated>2023-12-21T14:52:22.929Z</atom:updated>
            <content:encoded><![CDATA[<h3>Decoding the Mechanics: Understanding JavaScript Execution Fundamentals</h3><p>This blog introduces crucial concepts for understanding how Javascript works under the hood.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wRqupLrd3zApGdBFIAU_5Q.jpeg" /></figure><p>This is what we will cover in this blog:</p><ol><li>Execution Environment Heap</li><li>Execution Environment Call Stack</li><li>Web APIs</li><li>Callback Queue</li><li>Event Loop</li><li>Microtask Queue</li><li>An example to understand these concepts</li><li>Summing up</li></ol><h3>Execution Environment Heap</h3><p>In the realm of JavaScript, the execution environment’s “heap” plays a crucial role in managing memory during program runtime. The heap is a region of memory where dynamic memory allocation occurs, particularly for objects and variables that don’t have a fixed size. When a JavaScript program is executed, the heap is responsible for storing and organizing objects, functions, and other data structures created during the program’s execution. It is a key component of the runtime environment, facilitating the allocation and deallocation of memory as needed. JavaScript developers benefit from the automatic memory management provided by the heap, as it allows for more flexible and dynamic coding without the burden of manual memory management. However, it’s important for developers to be mindful of memory usage and potential memory leaks to ensure optimal performance in their applications. The garbage collection also plays an essential role claiming memory no longer in use.</p><h3>Execution Environment Call Stack</h3><p>The call stack is another critical component of the execution environment, closely intertwined with the heap. The call stack is a data structure that keeps track of the execution context of a program. Every time a function is invoked, a new frame is pushed onto the call stack, representing the context of that function call, including parameters, local variables, and the return address. As functions complete their execution, their frames are popped off the stack. The call stack operates on a Last In, First Out (LIFO) basis, meaning the most recently invoked function is the first to be resolved. This sequential nature ensures that the program executes in a predictable order. If the call stack becomes too deep due to a large number of nested function calls or recursive operations, it can lead to a stack overflow, causing the program to terminate. Understanding the call stack is crucial for developers to comprehend the flow of their code and diagnose issues such as infinite loops or excessive recursion that may impact the stack’s integrity. Remember only one operation happens at the same a time, as Javascript Is a single thread language.</p><h3>Web APIs</h3><p>In the JavaScript execution environment, Web APIs (Application Programming Interfaces) play a pivotal role in facilitating interactions between web browsers and external resources. Web APIs are a set of functionalities and methods provided by the browser, allowing JavaScript to communicate with various web-related features. These APIs include, but are not limited to, the Document Object Model (DOM) API for manipulating the HTML and XML documents, the XMLHttpRequest or Fetch API for making HTTP requests, and the Geolocation API for obtaining the user’s location.</p><p>What makes Web APIs unique is that they operate asynchronously. When a web API is invoked, the browser initiates the operation but doesn’t wait for it to complete. Instead, the browser continues executing the remaining code. Once the API operation finishes, a callback function or a Promise resolves, allowing the program to handle the results.</p><p>Understanding how to leverage Web APIs is crucial for building dynamic and interactive web applications. Developers often use these APIs to fetch data from servers, update the user interface, or interact with various browser features. Effectively integrating Web APIs into JavaScript code enhances the functionality and user experience of web applications.</p><h3>Callback Queue</h3><p>The Callback Queue is closely associated with the concept of asynchronous programming, especially in the context of Web APIs and events. When an asynchronous operation is initiated, such as fetching data from a server or handling user events, the associated callback functions are not executed immediately. Instead, they are placed in the Callback Queue.</p><h3>Event Loop</h3><p>The event loop, another crucial part of JavaScript’s runtime, continually checks the call stack and the Callback Queue. If the call stack is empty, the event loop takes the first function from the Callback Queue and pushes it onto the call stack, initiating its execution. This mechanism allows asynchronous operations to be processed without blocking the main thread of execution.</p><p>For instance, when a user clicks a button triggering an asynchronous operation, the associated callback function is placed in the Callback Queue. The event loop then ensures that this callback is executed when the call stack is clear, preventing potential blocking of the user interface.</p><h3>Microtask Queue</h3><p>In the JavaScript execution environment, the Microtask Queue, is a queue that holds tasks with higher priority than regular tasks in the Callback Queue. Microtasks are typically used for handling promises and other high-priority asynchronous tasks.</p><p>When a promise is settled (either resolved or rejected), its associated callbacks (<strong>.then()</strong> or <strong>.catch()</strong>) are queued in the Microtask Queue.</p><h3>An example to understand these concepts</h3><p>Look at the following example:</p><pre>console.log(&quot;a&quot;);<br>setTimeout(() =&gt; {<br>  console.log(&quot;b&quot;);<br>})<br>console.log(&quot;c&quot;);</pre><p>Before reading this blog, you could expect the program to print <em>a, b, c</em>. But the reality is that it prints a, c, b. Can you guess what is the reason?</p><p>While the setTimeout operation is handled the latest console.log is executed by the Call Stack. The setTimeout callback function is placed in the Callback Queue, and despite the delay being 0, is not executed until the Call Stack is empty. The Event Loop is responsible for pushing the callback onto the Call Stack, which initiates its execution.</p><p><a href="https://www.youtube.com/shorts/dqEbOPWTzkc">Here</a> is a video I published in my Youtube <a href="https://www.youtube.com/@aLosada_dev">channel</a> talking about this example.</p><h3>Summing up</h3><p>All these concepts are crucial for managing the order of execution in asynchronous JavaScript. It’s important to learn about them to know how Javascript behaves. Together, these components form the foundation of a versatile and efficient JavaScript runtime, empowering developers to create interactive and responsive web applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=580e4ba0337c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I’ve started a YouTube channel!]]></title>
            <link>https://medium.com/@alvarolosada/ive-started-a-youtube-channel-2e9ee173baba?source=rss-8d07b8433061------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e9ee173baba</guid>
            <category><![CDATA[youtube]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Alvaro Losada]]></dc:creator>
            <pubDate>Fri, 10 Nov 2023 16:59:12 GMT</pubDate>
            <atom:updated>2023-11-10T16:59:12.872Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dgnjeI5M8j2ePZXAQbdMDg@2x.jpeg" /></figure><p>Heyyy everyone!</p><p>I wanted to update you. I have started a new YouTube channel. It will be focused on content about Typescript, but also some React and design system.</p><p>There you will find mostly shorts, so you can learn interesting things in a short amount of time.</p><p><a href="https://www.youtube.com/@aLosada_dev">Here</a> is the link to the channel and to my first <a href="https://youtube.com/shorts/NifpBE0It_o?si=03umjWvWznA32h9x">short</a>.</p><p>Hope to see you there!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e9ee173baba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimise your code: An easy time complexity reduction that will blow your mind]]></title>
            <link>https://medium.com/@alvarolosada/optimise-your-code-an-easy-time-complexity-reduction-that-will-blow-your-mind-4e9b21615fd9?source=rss-8d07b8433061------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e9b21615fd9</guid>
            <category><![CDATA[javascrıpt]]></category>
            <category><![CDATA[code-quality]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[complexity]]></category>
            <dc:creator><![CDATA[Alvaro Losada]]></dc:creator>
            <pubDate>Sat, 08 Jul 2023 15:42:47 GMT</pubDate>
            <atom:updated>2023-12-21T14:53:52.451Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UzcmPlE9OXBF23LD" /></figure><p>Perhaps the title has caught your attention. Before you start reading, I have to tell your there is a 99% chance this blog post it’s not going to blow your mind as it says, but if you are in the other 1%, maybe it can mean a lot to you</p><p>Let’s dive right in!</p><p>We are going to work here in a small problem. Imagine with have a list of 1000 objects (it can be three too, as in the example shown below ). You are asked to <strong>remove</strong> some of these elements. These alemana are coming in an array as a second parameter. The length of this array could be 1, 2 or 1000 (meaning all the elements have to be removed).</p><p><strong>What is the first thing you think of?</strong> If you use Javascript normally, I guess you will jump into the code thinking about using a <strong>for</strong> loop as a good idea, and inside it, check if the element is included in the second parameter array (you could do it using <strong>includes</strong> built-in method, for example). This approach would have the problem solved in just a couple of minutes. And it works.</p><p>So, what does that mean exactly?</p><p>Ask yourself a question. Have you taken into account that in the worst case-scenario your code is iterating 1.000 * 1.000 = <em>1.000.000 times</em>. This means time complexity would be O(n2) and your function would decrease performance.</p><pre>const files = filesArray.filter(file =&gt; filesToRemove.includes(file))</pre><p>We did a first approach, but we can refactor the code and reduce its complexity.</p><p><strong>How we can improve this code?</strong> 99 times out of 100, the most common solution is to sacrifice memory in exchange for a time improvement. If we can archive 1.000 + 1.000 = <em>2.000 iterations</em> in the worst case, or what means the same, a time complexity of O(n), we will observe a huge performance improvement. We can do it applying just a few changes.</p><pre>_([{ id: 1}, {id: 3}, {id: 5}], [{id: 3}])<br><br>// array to object<br>const filesIdx: Record&lt;string, unknown&gt; =<br> filesArray.reduce(<br>  // { 1: { id: 1}, 3: { id: 3}, 5: { id: 5}}<br>  (prev, curr) =&gt; {...prev, [concatIdType(curr)]: curr}},<br>  {}<br> );<br><br><br>// visit items<br>if (filesToRemove) {<br> filesToRemove.forEach(<br>  file =&gt; {<br>   if (!filesIdx[String(concatIdType(file))] return;<br>   delete files[String(concatIdType(file))] // { 1: { id: 1}, 5: { id: 5} }<br>  }<br> );<br>}<br><br>// resultant values to array<br>const files = Object.values(filesIdx); // [{id: 1}, { id:5}]</pre><p>With that newfound knowledge, let’s break down this process into steps.</p><p>First, we need to convert our array of objects into an object, which declares as keys the unique values of the array. This procedure will also remove duplicates in case they exist.</p><p>Then, we visit each item in the object and remove all the object keys that exist in the second array.</p><p>Finally, we convert the resultant object into an array, with the second parameter values removed from the original one.</p><h3>Final words</h3><p>In this blog post, I just wanted to tell you about an small trick that can make your code much more performant. There are thousands of other performance improvements, but I was working on a feature at work last week that led me to implement this change, and I didn’t want to miss the chance to pass it on to someone else who might find it useful.</p><p>If you’re really ready to take your skills to the next level, don’t forget to hit the subscribe button in my profile ✉️.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e9b21615fd9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[File-Based Routing in Next.js 13+]]></title>
            <link>https://medium.com/@alvarolosada/file-based-routing-in-next-js-13-ac7829f55372?source=rss-8d07b8433061------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac7829f55372</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[routing]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Alvaro Losada]]></dc:creator>
            <pubDate>Sat, 01 Jul 2023 14:23:01 GMT</pubDate>
            <atom:updated>2023-12-21T14:52:49.976Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*6T9LoSsNB_VPX_vaEbI_XQ.png" /></figure><p>Routing has always been one of the main strengths of Next.js. Next.js uses file-based routing. How this approach works is representing the router using the file system along the page concept instead to having to configure a router yourself (with react-router-dom or any other library).</p><p>You can access to its superb documentation <a href="https://nextjs.org/docs/pages/building-your-application/routing">here</a>.</p><h3>The basics</h3><p>First of all, it’s important to notice routing hasn’t suffer big changes in version 13 and almost the same name convections are still valid.</p><p>You have <a href="https://github.com/aLosada7/file-based-routing-next-13">here</a> completely free access to the Github repository with all the examples we are going to see in this post.</p><p>The main thing affecting routing in the new version comes with the introduction of a new directory, called <em>app</em>, instead of the already known <em>pages</em>.</p><p>Since v13, there is where the index router go, but also the rest of the pages have to be moved to the app directory. To create new routes we have to do the same than before, but adding to the folder a file called <em>page.{tsx, jsx, js}</em>. Remember files must be named <em>page</em> in order to be considered a page by the routing.</p><p>With that newfound knowledge, let’s break down this process into steps.</p><p>First, we have to create a Next.js application (you can just run <em>npx create-next-app@latest — experimental-app</em> setting all values you are asked by default). Then, if we open the project in VSC or your favourite editor, we can see a <em>page.tsx</em>which was created by default in the scaffolder (inside the <em>app</em> directory). This will be the Home page of your application.</p><p>If you want to create new nested routes, you need to create new folders, and inside them, a new <em>page</em> file. Just doing this, Next.js will create new routes for you.</p><p>Let’s do an example. Create a new page file inside an about folder. Basically what you have to do is adding inside the <em>apps</em> folder an <em>about/page.tsx </em>with the following code.</p><pre>const About = () =&gt; &lt;div&gt;about&lt;/div&gt; <br>export default About;</pre><p>Run <em>npm run dev</em> and navigate to <em>localhost:3000/about</em>. Here is an screenshot to illustrate the above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uPUpLjqI2bRE71Cvi-1V6A.png" /></figure><p>We can create a new level in a simple way with a <em>about/us/page.tsx </em>under the <em>app</em> folder. Write the following code:</p><pre>const Us = () =&gt; &lt;div&gt;about us&lt;/div&gt;; <br>export default Us;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uPUpLjqI2bRE71Cvi-1V6A.png" /></figure><p>On the other side, if we try a location with a non-existing page in the router, we get the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*htEGUsiz5enCZwDAHEdP3Q.png" /></figure><h3>Dynamic routes</h3><p>Many times routes are dynamic, and for example, we might need to fetch data depending a value coming from the url.</p><p>Let’s take an easy but explanatory use case. We have a blog, and we want to manage dynamically different posts.</p><p>The term <em>slug</em>, which<em> </em>is<em> </em>probably already known to you, it’s all we need to handle the pathname. To tell Next.js something is dynamic we use [slug] as the folder name. Inside, we have to create our <em>page</em> file as always.</p><pre>const Post = ({ params }: { params: { slug: string } }) =&gt; { <br>  return &lt;div&gt;My Post: {params.slug}&lt;/div&gt;; <br>} <br>export default Post;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ui57-TH4hIiRuOMgTGV4og.png" /></figure><p>We can also do this when we have more than one segment. In this case we call the folder <em>[…slug]</em>. Under app we can create a clothes<em>/[…slug]/page.tsx. </em>This will allow catching all segments. It means if you browse for <em>localhost:3000/shop/women/jeans </em>you will get women and jeans values. Here is the piece of code:</p><pre>const Clothes = ({ params }: { params: { slug: string[] } }) =&gt; { <br>  return ( <br>    &lt;&gt; <br>      {params.slug.map((slug) =&gt; ( <br>        &lt;div key={slug}&gt;<br>          {slug}<br>        &lt;/div&gt; <br>      ))} <br>    &lt;/&gt; <br>  ); <br>}; <br>export default Clothes;</pre><p>And here is the result to illustrate the above:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UCzSmO5SIkT9w4DkBwBpaw.png" /></figure><p>You can find all this documentation and more about dynamic params <a href="https://nextjs.org/docs/app/building-your-application/routing/dynamic-routes">here</a>.</p><h3>Router grouping</h3><p>The last concept I want to talk about is router grouping. There are some cases, like when people you want to create a marketing site, but in the same app, have under authentication a dashboard and other app features. If you want to keep things separated but together, router grouping might be a good solution.</p><p>Let’s see it in one example.</p><p>Under the <em>app</em> directory, create a folder named <em>(marketing).</em> Then, inside, create a <em>home/page.tsx </em>and add it some text. We can add more like pricing, … . On the other side, we create a folder named <em>(product)</em>, and under it a <em>dashboard/page.tsx</em>.</p><p>This way we can create different layouts, providers, … that group only certain router.</p><p>Probably you have asked yourself what happens if there is more than one home folder. In that case, Next.js will take always the first browsing by the app folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-ZRwGryLsGCsjxo4okHdIg.png" /></figure><h3>Summing up</h3><p>It is undisputed that the routing system proposed by Next.js is very easy compared to many other tricky developments needed to both archive basic routing and manage query params in your router.</p><p>If Next.js is the right tool for your appliccation, you are lucky you will have probably if not the best, a top and easy way of handling application routes.</p><p>If you’re really ready to take your skills to the next level, don’t forget to hit the subscribe button in my profile ✉️.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac7829f55372" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[20 things to check when reviewing Pull Requests]]></title>
            <link>https://medium.com/@alvarolosada/20-things-to-check-when-reviewing-pull-requests-f3bb8e382a94?source=rss-8d07b8433061------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3bb8e382a94</guid>
            <category><![CDATA[pull-request]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[feedback]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Alvaro Losada]]></dc:creator>
            <pubDate>Sat, 10 Jun 2023 17:35:51 GMT</pubDate>
            <atom:updated>2023-12-21T14:54:13.278Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GXqrVigEvUyNeMUWnhdNcg.png" /></figure><p>Reviewing Pull Requests is an important part of our jobs. It helps not only to keep the codebase clean and find possible bugs, but it is also part of the learning process that we experience as developers. It’s crucial to understand that this is one of the best ways to grow.</p><p>As publisher, you should also bear in mind about these things you might need to review when working in your developments. I advice you to take a close look at the diff before publishing a PR, as it helps you to find many small issues which will save time to the reviewers.</p><p>Here are 20 advices that will ensure code (more of them are not just for React code) will be maintainable. These are for sure not the only things that you need to check in PRs, as the code might be more complex or have other crucial guidelines. These are just some things I have been writting down during my times reviewing PRs</p><p>1 — <strong>Do</strong> <strong>not</strong> use hardcoding values directly in your functions</p><p><strong>Instead</strong> pass a default value to your functions (JS default values). <a href="https://testing.googleblog.com/2020/08/testing-on-toilet-avoid-hardcoding.html">Here</a> is an small article you can read to gain more understanding.</p><p>2 — Do not use only return in guard classes, as when applying format it could break your code</p><p><strong>Instead</strong> use curly braces or &amp;&amp; to evaluate conditions</p><p>3 — Do not mock a file without using it afterwards. It could increase the time your test take to be run</p><p>4 — Could any component be <strong>migrated</strong> to <strong>Typescript</strong>? If your application supports Typescript adding type-checking is the minimum benefit that you will obtain, and this is so helpful. What is more, you will be probably finding props, types, functions… which are not used in the code</p><p>5 — Each test <strong>tests</strong> just the right thing. Create as many test as you need to cover not just the happy path, but also the edge cases. And if you discover a bug, add some tests to be sure it doesn’t appear again. In React, pay special attention to hooks. As they are functions, they should be doing just one thing (single responsibility)</p><p>6 — Check if all <strong>effects</strong> are needed. Effects might cause side effects, so whenever it is possible to avoid them, do it, because testing them might be complicated</p><p>7 — When passing <strong>keys</strong>, do not use index. <strong>Instead</strong> assign each item of the object an unique identifier. Your application will perform better</p><p>10 —<strong> Parsing numbers</strong> with <strong>+ </strong>can fail, as you could run into some surprising corner cases. Cast values the right way. If you have Sonar configured, doing this should be shown as a code smell</p><p>11 —Use <strong>aria-label</strong> in repeated HTML elements (as buttons) in the same interface. Other aria-attributes are also important and you must ensure they are being used properly (aria-hidden, aria-invalid, aria-describedby, aria-expanded, …)</p><p>12 — Components should be <strong>agnostic</strong> of where they are used</p><p>13 — From v17 we don’t need to have React identifier in scope (transpiler job). If you are using a previous version, bear it in mind, as this might cause your code to break in production</p><p>14 — If you use S<strong>torybook</strong> review there are not missing cases in your stories. An scalable application has integration <strong>tests</strong>, but sometimes they don’t test all the cases, remember to be sure stories do it</p><p>15 — Do not use <strong>enums</strong> directly from a contract. If you happen to run into this, create a type instead</p><p>16 — Separate <strong>logic</strong> from the <strong>UI layer</strong> (whenever is possible). Favor stateless components</p><p>17 — Use <strong>object notation</strong> for responsive styles. It will reduce the usage of media queries and make your code much more readable</p><p>18 — Use tokens whenever it’s possible. If you are working with a design system, it’s better to define some tokens (spacing, colours, …) and use them throughout the codebase</p><p>19 — Understand the usages of the logical OR <strong>??</strong> and the nullish coalescing operator <strong>|| </strong>and think about possible consequences</p><p>20 — If as a team you have defined some guidelines, document them correctly so all the members of the team (including new ones) can use them easily</p><p>This are just a few things I take into account when reviewing a Pull Request. There are probably many more depending on the language, framework or the piece of code, but reading them from time to time always helps me to start writting feedback in PRs. Remember to be always polite when writing feedback</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3bb8e382a94" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a component library. The Alert component]]></title>
            <link>https://medium.com/@alvarolosada/creating-a-component-library-the-alert-component-f69aee55bde7?source=rss-8d07b8433061------2</link>
            <guid isPermaLink="false">https://medium.com/p/f69aee55bde7</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[components]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[design-systems]]></category>
            <dc:creator><![CDATA[Alvaro Losada]]></dc:creator>
            <pubDate>Fri, 09 Dec 2022 10:38:49 GMT</pubDate>
            <atom:updated>2023-12-21T14:55:07.630Z</atom:updated>
            <content:encoded><![CDATA[<h4>Join me in the new series of blogs which will build a complate reusable components library in React</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gsv3VA7Ki-wrNo8OjMpscg.png" /></figure><p>An alert basically displays a short important message and optionally several actions that can be taken. Its main purpose is attracting the user’s attention without interrupting the user’s task.</p><h3>Base component</h3><p>The most basic alert just shows a text inside a dialog box. Let’s create a basic alert using a <em>div</em> and the <em>Text</em> component.</p><pre>import { ReactNode } from &quot;react&quot;;<br>import { css } from &quot;@emotion/react&quot;;<br><br>import { Props, textSans } from &quot;@edene/foundations&quot;;<br>import { Text } from &quot;@edene/components&quot;;<br><br>const alert = css`<br>   font-family: Lato, Arial, sans-serif;<br>   font-size: 14px;<br>   line-height: 1.5;<br>   font-weight: 400;<br>   background-color: #e1f9f5;<br>   color: rgb(48, 144, 142);<br>  <br>   display: flex;<br>   justify-content: space-between;<br>   align-items: center;<br>  <br>   padding: 0.75rem 1.25rem;<br>   margin-bottom: 1rem;<br>   border: 1px solid transparent;<br>   border-radius: 0.25rem;<br>`;<br><br>export interface AlertProps extends Props {<br>   children: ReactNode;<br>}<br><br>export const Alert = (props: AlertProps) =&gt; (<br>   &lt;div<br>    role=&quot;alert&quot;<br>    css={alert}<br>    {...props} // necessary to override other props as className<br>   &gt;<br>    &lt;Text&gt;{props.children}&lt;/Text&gt;<br>   &lt;/div&gt;<br>);</pre><p>The <em>alert</em> role is used to communicate an important and usually time-sensitive message to the user. The <em>css</em> attribute comes from <em>Emotion</em>.</p><pre>&lt;Alert&gt;Alert&lt;/Alert&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gHFXNWmZXPb4MeLqLNGFdg.png" /></figure><p>It’s time to introduce an action. The action has to be linked with the alert. The most common actions are dismissing, linking to another page or lifting a modal box.</p><pre>import { Props, textSans } from &#39;@edene/foundations&#39;;<br>import { Text } from &#39;@edene/components&#39;;<br><br>const alert = css`<br>    font-family: Lato,Arial,sans-serif;<br>    font-size: 14px;<br>    line-height: 1.5;<br>    font-weight: 400;<br>    background-color: #E1F9F5;<br>    color: rgb(48, 144, 142);<br><br>    display: flex;<br>    justify-content: space-between;<br>    align-items: center;<br><br>    padding: 0.75rem 1.25rem;<br>    margin-bottom: 1rem;<br>    border: 1px solid transparent;<br>    border-radius: 0.25rem;<br>`;<br><br>export const alertActions = css`<br>    display: grid;<br>`;<br><br>export interface AlertProps extends Props {<br>    actions?: ReactNode;<br>    children: ReactNode;<br>}<br><br>export const Alert = (props: AlertProps) =&gt; (<br>   &lt;div<br>    role=&quot;alert&quot;<br>       css={alert}<br>    {...props}<br>   &gt;<br>       &lt;Text&gt;{props.children}&lt;/Text&gt;<br>    {props.actions &amp;&amp; &lt;div css={alertActions}&gt;{props.actions}&lt;/div&gt;}<br>   &lt;/div&gt;<br>);</pre><pre>&lt;Alert actions={&lt;Button variant=&quot;link&quot; color=&quot;success&quot;&gt;Dismiss&lt;/Button&gt;}&gt;<br>    This is an alert with a dismiss button<br>&lt;/Alert&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aqha1pldhddCj7EBn6C19Q.png" /></figure><p>Lastly, it might be useful to define different types of alerts. Apart from the positive/success one, we can have different colors for informative and danger alerts (it could be others). In order to archieve this, we will define a new property for the component. Depending its value, we will be basically applying different styles for both the text and background colors.</p><p>Here is the final implementation of the component.</p><pre>import { Text } from &#39;@edene/components&#39;;<br><br>const alert = (type: &#39;success&#39; | &#39;info&#39; | &#39;danger&#39;) =&gt; css`<br>  font-family: Lato,Arial,sans-serif;<br>    font-size: 14px;<br>    line-height: 1.5;<br>    font-weight: 400;<br><br>    ${type === &#39;success&#39; &amp;&amp;<br>        `background-color: #E1F9F5;<br>        color: rgb(48, 144, 142);`}<br>    ${type === &#39;info&#39; &amp;&amp;<br>        `background-color: #EBF6FA;<br>        color: #2A789A;`}<br>    ${type === &#39;danger&#39; &amp;&amp;<br>      `background-color: #f8d7da;<br>      color: #DC3545;`}<br><br>    display: flex;<br>    justify-content: space-between;<br>    align-items: center;<br><br>    padding: 0.75rem 1.25rem;<br>    margin-bottom: 1rem;<br>    border: 1px solid transparent;<br>    border-radius: 0.25rem;<br>`;<br><br>export const alertActions = css`<br>    display: grid;<br>`;<br><br>export interface AlertProps {<br>  type: &#39;success&#39; | &#39;info&#39; | &#39;danger&#39;;<br>  actions?: ReactNode;<br>    children: ReactNode;<br>}<br><br>export const Alert = (props: AlertProps) =&gt; (<br>   &lt;div<br>    role=&quot;alert&quot;<br>       css={alert(props.type)}<br>    {...props}<br>   &gt;<br>       &lt;Text&gt;{props.children}&lt;/Text&gt;<br>    {props.actions &amp;&amp; &lt;div css={alertActions}&gt;{props.actions}&lt;/div&gt;}<br>   &lt;/div&gt;<br>);</pre><p>Here is the end use and the result.</p><pre>&lt;&gt;<br>  &lt;Alert type=&quot;success&quot;&gt;This is a success alert&lt;/Alert&gt;<br>  &lt;Alert type=&quot;info&quot;&gt;This is a danger alert&lt;/Alert&gt;<br>  &lt;Alert type=&quot;danger&quot;&gt;This is a danger alert&lt;/Alert&gt;<br>&lt;/&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EJpQPqmZN53jUrRa9z6bUA.png" /></figure><p>This blog was previously published on my website <a href="https://alvarolosada.com/blog/creating-a-component-library-the-alert-component">blog</a>. If you want to know me, the Design System Edene, access other contents or read new publications early, check it out.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f69aee55bde7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Debugging CSS in Storybook without DevTools]]></title>
            <link>https://medium.com/@alvarolosada/debugging-css-in-storybook-without-devtools-ab6b9466e901?source=rss-8d07b8433061------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab6b9466e901</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[storybook]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Alvaro Losada]]></dc:creator>
            <pubDate>Wed, 19 Oct 2022 15:57:40 GMT</pubDate>
            <atom:updated>2023-12-21T14:53:05.572Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KjagYOQawk9mtnPCb0JhVw.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@pixabay/">Pixabay</a> on <a href="https://www.pexels.com/">Pexels</a></figcaption></figure><p>This post was originally posted on <a href="https://alvarolosada.com/blog/devtools-storybook">my personal blog</a>.</p><p>In the last months, I have developed a special interest in <strong>Design Systems</strong>. Design Systems are now part of my web development carrer so I am continously reading different articles and following companies at the forefront to learn as much as I can.</p><p><a href="https://storybook.js.org/">Storybook</a> team has worked a lot on simplifying programmers life when developing component libraries. Storybook is an open source library for building UI components and pages in isolation. Their library is really good easing documentation, UI development and testing tasks. For developers, all are advantages. But among all the benefits, I want to underline the potential benefits to non-technical contributors, and how this can be a key to turning an idea or business requirement into a fully functional feature which can be followed by everyone interested.</p><p>In this post I want to address one particular aspect. Developers, particulary web developers, open and close the DevTools hundreds of times a day. Maybe you did not know Storybook can help you to avoid some of them.</p><h3>Interesting addons to reduce DevTools dependency</h3><p>Reduce the ardous task of opening the DevTools, inspecting an element or traversing the DOM is now possible thanks to Storybook.</p><p>We are going to talk about three different utilties in this blog. The first thing you have to do is to install these three addons as <strong>dev dependencies</strong> and then add them to your <em>.storybook/main.js</em> file.</p><pre>{<br>...<br>	addons: [<br>		...,<br>		&#39;@storybook/addon-measure&#39;,<br>		&#39;@storybook/addon/outline&#39;,	<br>		&#39;@storybook/addon-viewport&#39;,<br>		...<br>	]<br>...<br>}</pre><p>Once you start Storybook, the three of them can be found on the toolbar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*rW68pALPHbmjgGkCj8uY6g.png" /><figcaption>Addons in Storybook toolbar</figcaption></figure><h3>Measure tool</h3><p>Helpful when you wanna take a look at the content area, padding or margin values. With this add-on you get a visual representation with the specific values. It has a lot of similarities with DevTools inspection. You will be saving time when assuring proper spacing and margin values are increments of 8 (this is recommended to create web designs, but also sometimes using 4 points) or to align your elements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qmFd4Cu76VwCbcieCP7tQQ.png" /><figcaption>Measure tool</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*jhP-1BDKc9Cswz8q8-gF3A.png" /><figcaption>Measure tool II</figcaption></figure><h3>Outline tool</h3><p>It helps you visualize the flow of your content, relationships between elements. The way it works is very simple, drawing different outlines around every single element in the preview panel (canvas).</p><p>I use it mainly as part of my <strong>visual tests</strong>. Visual testing catches bugs as cut-off elements, incorrect font-styles or broken layouts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*23dVMAaR6LDUhIUyd0yhhg.png" /><figcaption>Outline tool</figcaption></figure><h3>Viewport tool</h3><p>This tool is very similar to the built-in responsive view in Dev Tools, but directly integrated in Storybook. Moreover, using this add-on you won’t need to resize your stories so they wwill never be reloaded.</p><p>There is a default number of viewports defined (mobile, desktop, tablet), but this is totally customizable so you can add as many viewports as you want.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d1J_NFeags5U1boJgACVOQ.png" /><figcaption>Viewport tool</figcaption></figure><p>You can define this in your preview. I have several custom viewports defined which I use for every project I work in.</p><pre>export type Breakpoint =<br>    | &#39;mobile&#39;<br>    | &#39;mobileMedium&#39;<br>    | &#39;mobileLandscape&#39;<br>    | &#39;phablet&#39;<br>    | &#39;tablet&#39;<br>    | &#39;desktop&#39;<br>    | &#39;leftCol&#39;<br>    | &#39;wide&#39;;</pre><pre>export const breakpoints: Record&lt;Breakpoint,number&gt; = {<br>    mobile: 320,<br>    mobileMedium: 375,<br>    mobileLandscape: 480,<br>    phablet: 660,<br>    tablet: 768,<br>    desktop: 980,<br>    leftCol: 1140,<br>    wide: 1300,<br>};</pre><pre>// preview.ts<br>type ViewportMeta = {<br>    [key in Breakpoint]: {<br>        name: string;<br>        type: string;<br>    };<br>};</pre><pre>const viewportMeta: ViewportMeta | any = {<br>    mobile: {<br>        name: &#39;Mobile&#39;,<br>        type: &#39;mobile&#39;,<br>    },<br>    mobileMedium: {<br>        name: &#39;Mobile Medium&#39;,<br>        type: &#39;mobile&#39;,<br>    },<br>    mobileLandscape: {<br>        name: &#39;Mobile Landscape&#39;,<br>        type: &#39;mobile&#39;,<br>    },<br>    phablet: {<br>        name: &#39;Phablet&#39;,<br>        type: &#39;mobile&#39;,<br>    },<br>    tablet: {<br>        name: &#39;Tablet&#39;,<br>        type: &#39;tablet&#39;,<br>    },<br>    desktop: {<br>        name: &#39;Desktop&#39;,<br>        type: &#39;desktop&#39;,<br>    },<br>    leftCol: {<br>        name: &#39;Left Col&#39;,<br>        type: &#39;desktop&#39;,<br>    },<br>    wide: {<br>        name: &#39;Wide&#39;,<br>        type: &#39;desktop&#39;,<br>    },<br>};</pre><pre>const viewportEntries = Object.entries(breakpoints).map(([name, width]) =&gt; {<br>    return [<br>        name,<br>        {<br>            name: viewportMeta[name].name,<br>            styles: {<br>                width: `${width}px`,<br>                height: &#39;100%&#39;,<br>                padding: &#39;0&#39;,<br>            },<br>            type: viewportMeta[name].type,<br>        },<br>    ];<br>});</pre><pre>// viewport object<br>const viewport = {<br>    viewports: {<br>        ...Object.fromEntries(viewportEntries),<br>    },<br>};</pre><pre>// export viewport as parameters<br>export const parameters = {<br>    viewport,<br>};</pre><h3>Final words</h3><p>These add-ons are very helpful to reduce the time it takes to open and close DevTools, select and element in the page and inspect it or toggle device toolbar. I invested time when I was working on the interface of my blog that is now live on my <a href="https://alvarolosada.com/blog">website</a>.</p><p>You can check out Edene Storybook and try the add-ons <a href="https://master--62ed74f612c78f7bbe13743e.chromatic.com/">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab6b9466e901" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Efficient list rendering in React using Virtualization]]></title>
            <link>https://medium.com/@alvarolosada/virtualization-can-be-defined-as-the-creation-of-a-virtual-version-of-something-146c802ef9b0?source=rss-8d07b8433061------2</link>
            <guid isPermaLink="false">https://medium.com/p/146c802ef9b0</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[virtualization]]></category>
            <dc:creator><![CDATA[Alvaro Losada]]></dc:creator>
            <pubDate>Tue, 27 Sep 2022 17:45:17 GMT</pubDate>
            <atom:updated>2023-12-21T14:54:30.793Z</atom:updated>
            <content:encoded><![CDATA[<h4>Virtualize large lists can improve the performance of your application</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AN84FGNm5okHdHbx_AC8jA.jpeg" /></figure><blockquote><em>This is the first of two blog posts regarding virtualization in React</em></blockquote><p>Virtualization can be defined as the creation of a virtual version of something. In the React context, it can be defined as the creation of a window that allows records to slide in and out of the view as the user scrolls through it. Virtualization can be really helpful reducing drastically the time your lists take to render, specifically when applied to long lists. This technique improves the performance of your web application. With virtualization, what matters the most is that there are only loaded into the virtual DOM those elements inside the viewport. React relies on the Virtual DOM to efficiently render only the components that have been updated.</p><p>Remember that this representation of the UI is syncronized afterwards with the “real” DOM using a <a href="https://reactjs.org/docs/reconciliation.html">diffing algorithm</a>. This is made in React by ReactDOM library.</p><p>DOM updates might cause various problems (there are many others):</p><ul><li>Slow initial rendering</li><li>Laggy scrolling</li></ul><p>Thanks to virtualization, we face these two. Despite all the optimisations introduced by React, for highly-performant applications we may need more.</p><h3>DOM reflow &amp; DOM repaint</h3><p>DOM reflow &amp; DOM repaint are two complex processes which explain better the cost of upgrading the real DOM.</p><p><strong>DOM reflow</strong> is the process to figure out positions and sizes of each element, all child elements and its adjacents in the viewport. This is a really expensive process.</p><p><strong>DOM repaint</strong> is the process where the nodes from the tree are converted to pixels on the screen. This is how visibility is archieve.</p><p>These two process are triggered every time there is an update to be made, what makes updating the DOM expensive for the web browser.</p><h3>React-window</h3><p><a href="https://github.com/bvaughn/react-window">React-window</a> comes as an open-source solution to face the problems caused when a huge number of elements have to be shown in the screen, tackling slow initial rendering and laggy scrolling. At the same time, helps virtualization, one of the biggest problems of highly-performant React application.</p><p>According to its creator, Brian Vaughn, react-window is a complete rewrite of <a href="https://github.com/bvaughn/react-virtualized">react-virtualized</a> (which you may have heard about), faster and with a smaller bundler size. It constains all the essential functionalities of react-virtualized.</p><p>React-window can be used with other related libraries, maximizing its performance. Here are two of the most useful I have found.</p><ul><li>Infinite Loader — Avoids oftaining data before its required (until you scroll to fit more)</li><li>Autosizer — Calculate the available viewport to adjust the number of elements which fit in the view</li></ul><h3>Let’s do it</h3><p>Let’s implement a simple virtualization list.T o use this all together, first you have to add to your project the following dependencies (rember to add the types if your project uses Typescript):</p><pre>yarn add react-window react-virtualized-auto-sizer react-window-infinite-loader<br>yarn add -D @types/react-window @types/react-virtualized-auto-sizer @types/react-window-infinite-loader</pre><h3>Virtual List component</h3><p>The Virtual List component is complex, but once i has been understood you just have to use it properly to get the most from it.</p><pre>import {<br>  cloneElement,<br>  CSSProperties,<br>  forwardRef,<br>  ReactElement,<br>  useEffect,<br>  useRef,<br>} from &#39;react&#39;;<br>import { FixedSizeListProps, VariableSizeList } from &#39;react-window&#39;;<br>import InfiniteLoader from &#39;react-window-infinite-loader&#39;;<br>import AutoSizer from &#39;react-virtualized-auto-sizer&#39;;</pre><pre>export interface VirtualListProps<br>  extends Omit&lt;<br>    FixedSizeListProps,<br>    | &#39;children&#39;<br>    | &#39;innerElementType&#39;<br>    | &#39;height&#39;<br>    | &#39;width&#39;<br>    | &#39;itemSize&#39;<br>    | &#39;itemCount&#39;<br>  &gt; {<br>  hasNextPage: boolean;<br>  isNextPageLoading: boolean;<br>  items: unknown[];<br>  getItemsHeight?: (index: number) =&gt; number;<br>  itemSize?: number;<br>  loadNextPage: () =&gt; void;<br>  Row: ReactElement;<br>}</pre><pre>export interface VirtualListItemProps {<br>  index: number;<br>  style: Record&lt;string, unknown&gt;;<br>}</pre><pre>/**<br> * The Inner component of the virtual list. This is the &quot;Magic&quot;.<br> * Capture what would have been the top elements position and apply it to the list.<br> **/<br>const Inner = forwardRef&lt;HTMLDivElement, React.HTMLProps&lt;HTMLDivElement&gt;&gt;(<br>  function Inner({ children, ...rest }, ref) {<br>    return (<br>      &lt;div {...rest} ref={ref}&gt;<br>        &lt;ul&gt;{children}&lt;/ul&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>);</pre><pre>function VirtualListRow({<br>  Row,<br>  isItemLoaded,<br>  index,<br>  style,<br>}: {<br>  isItemLoaded: (index: number) =&gt; boolean;<br>  Row: ReactElement;<br>  index: number;<br>  style: CSSProperties;<br>}) {<br>  if (!isItemLoaded(index)) return &lt;div&gt;&lt;/div&gt;;<br>  return cloneElement(Row, { index, style });<br>}</pre><pre>export default function VirtualList({<br>  // Are there more items to load?<br>  hasNextPage,</pre><pre>  // Are we currently loading a page of items?<br>  isNextPageLoading,</pre><pre>  // Array of items loaded so far.<br>  items,</pre><pre>  // Callback function responsible for loading the next page of items.<br>  loadNextPage,<br>  getItemsHeight,<br>  itemSize,<br>  Row,<br>}: VirtualListProps) {<br>  useEffect(() =&gt; {<br>    if (listRef &amp;&amp; listRef.current &amp;&amp; listRef.current.resetAfterIndex) {<br>      listRef.current.resetAfterIndex(0);<br>    }<br>  }, [items]);</pre><pre>  const listRef: any = useRef({});<br>  // If there are more items to be loaded then add an extra row to hold a loading indicator.<br>  const itemCount = hasNextPage ? items.length + 1 : items.length;</pre><pre>  // Only load 1 page of items at a time.<br>  // Pass an empty callback to InfiniteLoader in case it asks us to load more than once.<br>  // eslint-disable-next-line @typescript-eslint/no-empty-function<br>  const loadMoreItems = isNextPageLoading ? () =&gt; {} : loadNextPage;</pre><pre>  const getItemHeight = (index: number) =&gt; {<br>    if (getItemsHeight) return getItemsHeight(index);</pre><pre>    return itemSize || 40;<br>  };</pre><pre>  // Every row is loaded except for our loading indicator row.<br>  const isItemLoaded = (index: number) =&gt; !hasNextPage || index &lt; items.length;</pre><pre>  return (<br>    &lt;AutoSizer&gt;<br>      {({ height, width }) =&gt; (<br>        &lt;InfiniteLoader<br>          isItemLoaded={isItemLoaded}<br>          itemCount={itemCount}<br>          loadMoreItems={loadMoreItems}<br>        &gt;<br>          {({ onItemsRendered }) =&gt; (<br>            &lt;VariableSizeList<br>              height={height}<br>              itemCount={itemCount}<br>              itemSize={getItemHeight}<br>              onItemsRendered={onItemsRendered}<br>              ref={listRef}<br>              width={width}<br>              innerElementType={Inner}<br>            &gt;<br>              {({ index, style }) =&gt; (<br>                &lt;VirtualListRow<br>                  isItemLoaded={isItemLoaded}<br>                  Row={Row}<br>                  index={index}<br>                  style={style}<br>                /&gt;<br>              )}<br>            &lt;/VariableSizeList&gt;<br>          )}<br>        &lt;/InfiniteLoader&gt;<br>      )}<br>    &lt;/AutoSizer&gt;<br>  );<br>}</pre><p>Let’s break it down:</p><ul><li>I have defined the <strong>VirtualListProps</strong> interface in which I omit (Omit&lt;Type, Keys&gt;. contrary to Pick, removes from all the properties of type the keys selected), defining also the following parameters</li><li>hasNextPage → a boolean value which sets is there are more results available to be loaded. This information usually comes from the most recent API request</li><li>isNextPageLoading → a boolean value to know if new results are currently being fetched. This may be an in-flight flag in your Redux store for example, or it can be provided by swr</li><li>items → the array of items loaded so far. It is typed to unknown because it is the responsibility of the programmer to establish its type</li><li>getItemsHeight → a function to get the approximately height of an item</li><li>itemSize? → the exact height of an item if it is possible to be known</li><li>loadNextPage → the callback triggered when more items need to be loaded</li><li>Row → a ReactElement containing the item content</li><li><strong>VirtualListItemProps</strong> contains the properties for each item row. Includes the index (to be searched on the list) and the styles to paint it correctly.</li><li>The <strong>Inner</strong> component basically wraps the list</li><li>The <strong>VirtualListRow</strong> component creates a row for each existant element (meaning it has an index)</li><li>The <strong>VirtualList</strong> component itself, exported as default, puts together the Autosizer, the variable list and the virtual row. It also calculates the item height and triggers the callback when necessary.</li></ul><h3>Functionallity to get the list of items</h3><p>I am using <strong>swr/infinite</strong> to get an infinite list of items from a fake API I found on the Internet. I have created a custom hook which returns all the necessary to construct the list. We could also return a property to know if there is next page, but with API I know it will.</p><pre>import axios from &quot;axios&quot;;<br>import useSWRInfinite from &quot;swr/infinite&quot;;</pre><pre>import { IUserBase } from &quot;../model/user&quot;;</pre><pre>const SWR_KEY = &quot;users&quot;;</pre><pre>export interface IUseUserList {<br>	list?: IUserBase[];<br>	total: number;<br>	error?: Error;<br>	loading: boolean;<br>	size: number;<br>	setSize: (arg0: number) =&gt; void;<br>}</pre><pre>export const useUserList = (): IUseUserList =&gt; {<br>	const getKey = (pageIndex: number, previousPageData: string | any[]) =&gt; {<br>		// check if end has been reached<br>		if (previousPageData &amp;&amp; !previousPageData.length) return null;<br>		return `/${SWR_KEY}?page=${pageIndex}`;<br>	};</pre><pre>	const fetcher = (): any =&gt; {<br>		return axios.get(`https://gorest.co.in/public/v2/${SWR_KEY}?page=${size}`).then((res) =&gt; res.data);<br>	};</pre><pre>	const {<br>		data: list,<br>		error,<br>		isValidating,<br>		size,<br>		setSize,<br>	} = useSWRInfinite(getKey, fetcher, {<br>		revalidateFirstPage: false,<br>		revalidateAll: true,<br>	});</pre><pre>	return {<br>		list: (list || []).flat(),<br>		total: list ? list[0].total : 0,<br>		error,<br>		loading: isValidating,<br>		size,<br>		setSize,<br>	};<br>};</pre><h3>A component which uses it</h3><p>I created a container to wrap the data fetching functionality which directly calls a component in which the list is shown.</p><p>The UserItem uses the VirtualListItemProps to get the index and styles needed to place each item correctly on the screen.</p><pre>const UserItem = ({ index, style, ...props }: any) =&gt; {<br>	const user = props.list[index];</pre><pre>	return (<br>		&lt;Wrapper style={style}&gt;<br>			&lt;Content&gt;<br>				&lt;h4&gt;<br>					&lt;b&gt;{user.name}&lt;/b&gt;<br>					&lt;Badge status={user.status}&gt;{user.status}&lt;/Badge&gt;<br>				&lt;/h4&gt;<br>				&lt;p&gt;{`${user.email} | ${user.gender.charAt(0).toUpperCase()}${user.gender.slice(1)}`}&lt;/p&gt;<br>			&lt;/Content&gt;<br>		&lt;/Wrapper&gt;<br>	);<br>};</pre><p>First, we get the item and after that we render our item. You can check out the full component code <a href="https://github.com/aLosada7/react-virtualization/blob/master/src/user/components/UserListComponent.tsx">here</a>.</p><p>The result is the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pYVocqO7XhmiN-wnc7HOJQ.png" /></figure><h3>Final words</h3><p>Virtualization may seem challenging and complex at first, but once you understand how it works under the hood. I highly recommend you to invest time on implementing your own virtualized list, using react-virtualized or another library, as this complex concept will help you to understand a feature top-performant applications may implement.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=146c802ef9b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Edene and why did I use Nx to create it]]></title>
            <link>https://medium.com/@alvarolosada/building-edene-i-nx-the-key-which-gave-me-the-consistency-i-needed-315db4dd1bde?source=rss-8d07b8433061------2</link>
            <guid isPermaLink="false">https://medium.com/p/315db4dd1bde</guid>
            <category><![CDATA[nx]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[design-systems]]></category>
            <dc:creator><![CDATA[Alvaro Losada]]></dc:creator>
            <pubDate>Tue, 20 Sep 2022 16:08:02 GMT</pubDate>
            <atom:updated>2022-11-29T21:56:39.180Z</atom:updated>
            <content:encoded><![CDATA[<h4>I present you a totally customizable Design System to create efficient and eye catching user interfaces</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C7T6evPjy-aVy4W_N4IUwQ.jpeg" /></figure><blockquote><em>This is a series of blogs explaining everything about the Edene project, from arquitectural decisions, libraries and components implementations, decisions taken, … This blog has first been published in my </em><a href="https://alvarolosada.com/blog/edene-i"><em>blog</em></a><em>.</em></blockquote><h3>What is Edene?</h3><p>This is the main question I want to answer in this blog, and the main reason why this has to be the first post of the series.</p><p>Edene born as a React component library, but nowadays it is much more. Edene aims to give you eveything you need to create a Design System by creating a visual consistency. The result is a set of standards to manage design at scale where you can be focused on creating beautiful user experience.</p><p>If we dig into the project, Edene is made up of a set of libraries: the foundations (core) which contains all the guides and tokens needed to design your product, and three different implementation, with each of them giving meaning to the fundamentals.</p><p>The first of this implementations (libraries) consist of a list of completely customizable and reusable React <em>components</em>. Secondly, a collection of <em>animations</em> to create even more beautiful user experiences. Finally, a list of React hooks which will be used along with the components or on its own account. This last library is the only one fully independent of the foundations. There could exist others implementations in the future, For example, new component libraries for other frameworks like Angular or useful utilities for testing.</p><p>The following image shows a graph with the actual dependences between the existant libraries.</p><figure><img alt="Dependencies between apps and libraries" src="https://cdn-images-1.medium.com/max/1024/1*D_vUrlSEuqoLIGahYOGGbg.png" /></figure><p>As you can see below right, there is one more library I have not mentioned before, called <em>utils</em>, which for now only provides test and repository funcionality (ame although it is not published, it still appears on the dependency graph).</p><p>This graph is the result of a large amount of analysis and testing going from a completely disorganised repository to a clear distinction between each of the libraries and their responsibilities.</p><h3>Why a monorepo, and particularly Nx, solved the worst problems</h3><p>The monorepo is just the last step that gave me full confidence that the correct abstractions have been made. I started this project several months ago already using a monorepo, but with the idea in mind of having a single library which will contain Edene. There will be a couple of applications for testing purposes. But after not too long I realised I was not exploiting the full potential of Nx.</p><h3>Consistency</h3><p>A Design System can be defined as a collection of specifications describing a set of design primitives, reusable components, and arbitrary guidelines to ensure consistency and visual identity.</p><p>That means must a Design System does not mean only a “component library”, it goes further than that.</p><p>As I explained before, one of the first objectives was to separate what gives your app an identity (core variables/tokens, assets, …) from the different implementations. This is because frameworks have a lifetime, and although React looks set to be a long haul, we never know which framework we will be working tomorrow.</p><p>I am actually working a lot with React, and that’s why the first two implementations are two React libraries: one for components and another for hooks. This means it’s highly likely that in the future new implementations can be introduced, for Angular, Vue or any other web-tech. Another possibility would be to create a new library for common components that are shared across multiple mobile apps. This is what Spotify does with <a href="https://spotify.design/article/reimagining-design-systems-at-spotify">Encore</a>.</p><p>Having that in mind, I tried to keep a loosely coupled architecture that would allow a new implementation to be introduced more easily.</p><h3>Flexibility</h3><p>Nx allow you to start working in a new library in just a few minutes, thanks to its advanced code generator tools. This will also help you to add normalisation to your code at the same time you make it much more readable. You can add some configuration to improve your code quality. One of this aspects is eslint. You can add some new rules to improve core writting or simply follow Nx default preset and start working right after creating your library.</p><h3>All in one</h3><p>For Edene, I had an idea in mind in which there would be several applications: an application that would bring together the documentation (<em>edene-docs</em>), a set of example templates (<em>edene-template</em>) focused on the visual part, and there would be others which will include business logic (f<em>ood-delivery</em>). All of these applications will be using the different libraries (<em>core</em>, <em>components</em>) and have all of these updated independently would be very expensive (even more for one programmer). Bringing all together every single application is updated when any change occurs in any of the libraries on which they depend. This is also important to catch visual bugs by comparing the actual expected behaviour before the apps is deployed in production.</p><h3>Automation</h3><p>To speed up your workflow and ship higher quality code is necessary because reviewing code may not be sufficient to ensure that a pull request won’t break production .</p><p>For Edene, I am using GitHub Actions for now. It gives me all the necessary to introduce Continuous Integration (CI). At this point, it automatically run comprehensive UI test and deploys documentation, the Storybook and an example application.</p><h3>Edene current status</h3><p>After so much work, trial and error, I have reached a point where I truly believe the project is completely scalable, and working at it is comfortable for the programmer. Besides this, a project must be easy to contribute if you want it to success, and anyone could contribute from a small think to even a new implementation. There is some work left in guides for contributing it is just a matter of time to improve documentation.</p><p>On the other hand, and specifically speaking about the monorepo, I have to raise my voice and say that the use of Nx Console VS extension has given me total control over the projects and the apps at the monorepo, keeping test or linting at the top of his view. <a href="https://medium.com/nrwl/the-butterfly-effect-how-we-gave-linter-100x-boost-71a516750d19">This blog</a> shows an example of how simple they got a significant improvement in their linter rule. I follow the project closely and I know the team behind it is putting in a lot of effort to improve performance of every single process they implement.</p><p>The following image shows an example of how easy it is to manage each of the libraries and applications thanks to this VS extension.</p><figure><img alt="Projects in Nx Console" src="https://cdn-images-1.medium.com/max/790/1*l6LKC5_eD70P1JY8AvicOw.png" /></figure><h3>Final words</h3><p>After being working for months in this project, I had to admit I past hard times when struggled with architecture, organization or consistency. After putting a lot of efforts, I can say a monorepo tool as <em>Nx</em> has been <strong>key</strong> given me all the necessary to take the project to another level, making it at the same time <strong>“reachable”.</strong> Although the complexity is still high, the project is now easily scalable and highly flexible.</p><p>The challenges ahead consist of introducing more tests following different <a href="https://storybook.js.org/tutorials/ui-testing-handbook/react/en/introduction/">UI Testing Handbook</a> concepts. This tutorial made me understand how to face testing in the framework. Apart from this, I want to introduce more components and contemplate more use cases, add new interfaces to the template with graphs and other complex elements and improve the documentation.</p><p>As I had previously published on Linkedin, I am actively looking for contributors and companies that want to use Edene and take it to the new level.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=315db4dd1bde" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>