<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/">
<channel>
<title><![CDATA[Best Practices - Rafael Quintanilha]]></title>
<description><![CDATA[Essays about software engineering, web development, artificial intelligence, quantitative analysis, financial markets, books and tradition.]]></description>
<link>https://rafaelquintanilha.com/topic/best-practices/</link>
<image><url>https://rafaelquintanilha.com/content/images/2022/12/Logo-Design--2-.png</url><title>Best Practices - Rafael Quintanilha</title><link>https://rafaelquintanilha.com/topic/best-practices/</link></image>
<lastBuildDate>Sun, 04 Dec 2022 23:59:57 GMT</lastBuildDate>
<atom:link href="https://rafaelquintanilha.com/topic/best-practices/rss/" rel="self" type="application/rss+xml"/>
<ttl>60</ttl>
<item>
<title><![CDATA[React Best Practices: How to Write Better React Apps]]></title>
<description><![CDATA[A summary of modern React best practices, with tips that can be applied to real-world applications.]]></description>
<link>https://rafaelquintanilha.com/react-best-practices-how-to-write-better-react-apps/</link>
<guid isPermaLink="false">6383c14a14168e003dd8f7a8</guid>
<category><![CDATA[React]]></category><category><![CDATA[SEO]]></category><category><![CDATA[Best Practices]]></category>
<dc:creator><![CDATA[Rafael Quintanilha]]></dc:creator>
<pubDate>Wed, 07 Sep 2022 19:58:00 GMT</pubDate>

<content:encoded><![CDATA[<h2 id="what-is-react-and-why-use-it"><strong>What is React and why use it?</strong></h2>
<p>While web development isn’t <em>new</em>, some aspects of it are. In particular, frontend engineering is somewhat of a new term. Back in the day, you would see “web designers” and “webmasters”, but rarely <em>frontend developers</em>.</p>
<p>There’s a good reason for it - there was no need! Websites were simple, mostly static, and the bigger complexity was around designs, not functionality.</p>
<p>Needless to say, we are way past that now. Websites evolved into web apps, browsers became more powerful and the era of desktop applications is over, disrupted by the eruption of mobile devices. While it took some time for the consensus to establish in web apps and not in mobile apps, it seems to be fairly understandable now that web apps provide better availability, portability, and ease of use than native applications. And as mobile devices become more powerful, and optimizing for the web becomes a sexy engineering problem, the end result is an outburst of well-engineered, optimized, and resourceful applications right here, on the web.</p>
<p>But as we have learned from the history books, there’s no power vacuum. The web was set to reign, but who shall be the king? Enter <a href="https://reactjs.org/" rel="noopener noreferrer" target="_blank"><strong>React – a JavaScript library for building user interfaces</strong></a>.</p>
<p>This library maintained by the fine folks at Facebook took the market share and ended once and for all the <a href="https://medium.com/@ericclemmons/javascript-fatigue-48d4011b6fc4" rel="noopener noreferrer" target="_blank"><strong>JavaScript fatigue</strong></a>: that feeling everyone around in 2015 had. Every day a new frontend framework is competing for the top spot. Then eventually React appeared, people liked it, and the problem was settled.</p>
<p>This (not so) short introductory story is the answer to <em>what</em> React is and <em>why</em> you need it. Because React is a JavaScript library for the ever-growing frontend environment, you need it because it is popular, way maintained, liked, and used throughout the globe, in FAANGs and local shops. You can’t go wrong choosing React.</p>
<h2 id="what-makes-react-hard-to-learn-for-beginners"><strong>What makes React hard to learn for beginners?</strong></h2>
<p>React doesn’t have a particularly hard abstraction or technical conception. On the contrary, its single source of truth mantra has been a breeze for seasoned web developers.</p>
<p>However, this change in paradigm (for the better) can hit harder if you are used to using vanilla JavaScript or the last king, jQuery. Communication is rarely event-based, as opposed to what JavaScript typically enforces by design or with its backend counterpart, NodeJS.</p>
<p>Componentization is a concept that is easy to grasp but demands time to master. <a href="https://buttercms.com/blog/learn-react-hooks-by-writing-your-first-hook/" rel="noopener noreferrer" target="_blank"><strong>Hooks brought the functional flavor</strong></a> that seems to be the current trend, despite component lifecycles that may be more familiar to Java developers.</p>
<p>In short, what makes React hard for beginners is that <em>it is React</em>, not an adaption, a fork of a known framework, or an abuse of the JavaScript language. It’s a new paradigm, focused on User Interfaces, simplicity, and opinionated state management.</p>
<h2 id="react-best-practices"><strong>React best practices</strong></h2>
<p>Every language and framework has the so-called “best practices”, i.e., a community-accepted set of practices when using the tool. The following isn’t an exhaustive list of them, but an attempt to list the ones that typically concern the average developer.</p>
<h2 id="security"><strong>Security</strong></h2>
<p>Every software engineer that had code shipped to production had to go over this drill. Is the code secure? Are there flaws? Are they exploitable? Given the architecture of the web, this matter is even more flagrant.</p>
<p>However, I’d argue that React doesn’t pose any special security threat that any web application doesn’t have. Be aware of XSS attacks; store authentication tokens safely; sanitize HTML, and so forth.</p>
<h3 id="sanitize-html">Sanitize HTML</h3>
<p>By having its own <em>templating engine</em> that allows dynamic variables to be inserted into HTML, React exposes a security issue that every web developer should be aware of: injecting malicious code in HTML.</p>
<p>As the classical example goes, we don’t want users to pass any kind of script that can be rendered on an HTML page. Because of that, there’s a process called <em>sanitization</em>, where we allow only specific tags to be rendered on a page.</p>
<p>Imagine you have a CMS like ButterCMS and render the content generated by the content creator without any kind of filter. Well, <a href="https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml" rel="noopener noreferrer" target="_blank"><strong>React exposes the property</strong> <em><strong>dangerouslySetInnerHTML</strong></em></a> that serves this very purpose: get a raw HTML for an API, and render it in an element.</p>
<p>But the API isn’t named like that for nothing. Suppose this content contains a valid script that collects user information and posts it back to the attacker database: you’re essentially adding a trojan horse to your website!</p>
<p>In order to prevent such cases, you can use libraries like <a href="https://www.npmjs.com/package/sanitize-html" rel="noopener noreferrer" target="_blank"><strong>sanitize-html</strong></a> to allow only specific tags to be rendered. For example, if your goal is to render a blog post, you can allow only the traditional &#x3C;div>, &#x3C;p>, &#x3C;b>, &#x3C;i>, &#x3C;img>, etc tags, and block suspicious ones like &#x3C;script>.</p>
<h3 id="secure-apis">Secure APIs</h3>
<p>Although this isn’t a problem specific to React, this is a common problem faced by any front-end developer. We typically need to connect to our brothers in blood, the backend engineers, who have carefully crafted an interface for us to communicate.</p>
<p>However, this API often is <em>secured</em>, meaning that you need proper credentials to access it. The authentication process occurs mostly in the backend but is the front-end's job to keep the access token safe and sound.</p>
<p>There is a lot of <a href="https://stackoverflow.com/questions/3220660/local-storage-vs-cookies/3220802#3220802" rel="noopener noreferrer" target="_blank"><strong>debate about whether you should store it in the Local Storage or in cookies</strong></a>, and this matter warrants a post in itself. But while this is a personal choice and both can be used under the right circumstances, I find it crucial that you, as a developer, understand what the tradeoffs of each solution are.</p>
<p>I have used both, and suggest using cookies if you can. They provide more security layers and control, and if used with a compatible library in the backend, like <a href="https://flask-jwt-extended.readthedocs.io/en/stable/" rel="noopener noreferrer" target="_blank"><strong>Python’s Flask</strong></a>, the implementation is a breeze.</p>
<p>In any case, before judging your friend who stores a JWT in the Local Storage, try to understand where the flaw is. Saying “if your app JavaScript is compromised you are screwed” isn’t really an argument; once you’re compromised, well, you are screwed anyway. Understand your app’s needs first, and the rest should come naturally.</p>
<h3 id="install-linters">Install linters</h3>
<p>I mentioned before how good practices are nothing more than a community set of accepted practices, but as you have probably thought, this is subjective and hard to enforce.</p>
<p>Linters come to the rescue. There are awesome linters that will encapsulate a set of JavaScript or React-oriented best practices and complain whenever you drift off. This is great for ending an argument – people will often disagree on how to best handle a particular scenario. A linter, or a programmatic way to warn about an unexpected code usage, will act as the mighty judge, settling the matter once and for all (you need to agree on the linter first though).</p>
<p>Linters are also great for big teams, where many people touch a single file repeatedly. If everybody uses a linter, you cut off most of the inconsistencies, save development time and make reviewing code a breeze.</p>
<p>When coding, you shouldn’t focus too much on aesthetics. Sure, they are nice. But the less you need to worry about it, the better. Let developers focus on what they like, namely, code.</p>
<h2 id="testing"><strong>Testing</strong></h2>
<p>Think about that: you are already a developer, why would you do something manually? Programmers of course thought about that, and resisting the temptation of overengineering, also agreed on writing code for testing their own code. Isn’t it beautiful?</p>
<h3 id="leverage-react-debugging-utilities">Leverage React debugging utilities</h3>
<p>There are a set of React practices that are often neglected. <a href="https://reactjs.org/docs/error-boundaries.html" rel="noopener noreferrer" target="_blank"><strong>Error Boundaries</strong></a> are one of them.</p>
<p>When developing React applications, an interface is typically composed of several components in a tree that can escalate quickly. For that reason, if there’s an error in the application, it’s common to be lost in the hierarchy of components.</p>
<p>Error Boundaries can help you by raising the red flag on the exact node that experienced the flaw. More modern frameworks like <a href="https://buttercms.com/blog/what-is-react-remix/" rel="noopener noreferrer" target="_blank"><strong>React Remix</strong></a> leverage this concept to enhance user and developer experience. Give them a shot and caught the issues in the act.</p>
<p>Another way to add better-debugging tooling to your web app is to convert to TypeScript. Fortunately, TypeScript is widely adopted and integrated into the React ecosystem now. With TypeScript, you get top-notch auto-complete, caught errors on the act, and reduce runtime errors by leveraging features like type-checking. Pairing the typed JavaScript version with a good text editor like VSCode is a game changer for serious web development.</p>
<h3 id="invest-in-test-driven-development">Invest in test-driven development</h3>
<p>Beware when getting into the world of testing – you risk becoming addicted to it. In fact, some people like it so much that they develop backward! First, they create the test, <em>then</em> they write the code.</p>
<p>While this coding style isn’t for everyone, this is particularly interesting when developing a functional application or library. Suppose that you are working on a calculator. There are some well-defined cases that you want to handle, and it’s just fair that you work from there: you start by checking that addition works, then you move to multiplication, and handle edge cases.</p>
<p>For more complex applications, <a href="https://rafaelquintanilha.com/writing-tests-as-user-stories-in-react"><strong>I suggest treating your tests as user stories</strong></a>. Suppose you are working on a feature that needs to do X, Y, and Z. They are valid, strict metrics that you will be testing against. Once you established all the roadblocks, traps, and edge cases, it becomes way easier to just sit down and do what you already know.</p>
<p>Don’t know if this is for you? Well, <em>test</em> first, and then let me know (pun intended).</p>
<h3 id="install-react-testing-library">Install React Testing Library</h3>
<p>Everything I mentioned before about React taking over the power void can be applied to <a href="https://testing-library.com/docs/react-testing-library/intro/" rel="noopener noreferrer" target="_blank"><strong>React Testing Library</strong></a> or RTL. Designed for React and later adapted to other frameworks, the Testing Library took over hacky approaches like Enzyme, where developers would spend more time fixing tests than actually testing their applications.</p>
<p>React Testing Library has a simple API, a big community, and good principles, and should be your go-to library when unit testing your code.</p>
<h3 id="configure-user-events">Configure user events</h3>
<p>One of the main advantages of React Testing Library is abstracting away user events in single lines of code. For example: what if a user presses a specific key? Or if they move their mouse out of the window? Or focus on an input?</p>
<p>All those are events that can happen in a real app and oftentimes have a direct impact on what should happen next. For example, you can assert that a bouncing modal pops up if the user tries to leave the screen (it’s annoying but effective… what are you gonna do?). <a href="https://github.com/testing-library/user-event" rel="noopener noreferrer" target="_blank"><strong>A clear and simple API like the user events API</strong></a> from RTL is all you need in order to test like <em>user stories.</em></p>
<h2 id="components"><strong>Components</strong></h2>
<p>The heart of React, components are the best friend of the frontend developer. They encapsulate logic, UI blocks, and functionality. But how should you approach designing them?</p>
<h3 id="keep-component-creation-to-a-minimum">Keep component creation to a minimum</h3>
<p>Component creation should be understood as building a LEGO. You design the parts and glue them together. You start small, where each part is focused on its own job. It’s the UI equivalent to functional programming, where each function has a single purpose. In fact, components are functions! So the comparison holds even stronger.</p>
<p>When designing an interface, it’s often useful to draw it on a piece of paper. Using the same principle as in the test-driven approach, you have a <em>component-driven approach</em>. Start by designing your interface and what constitutes each part of it – maybe you have a side panel, a list of results in which every result has a call-to-action button… design them as an architect would design a living room, and the rest will flow naturally.</p>
<h3 id="introduce-state">Introduce state</h3>
<p>Using React for building user interfaces is nice, but if they are <em>static</em> there is nothing really exciting about them. Or at least nothing our predecessors, web designers, wouldn’t do with tools like Photoshop.</p>
<p>What transforms React into a really powerful library is its power to, well, <em>react</em> to users' interactions. That’s the heart and soul of frontend engineering – develop a nice UI, sure, but what good is a sleek-looking UI that isn't easy to use?</p>
<p>What solution does React brings to the table? The app or component <em>state</em> will dictate how your UI should behave. For example, it can display an error message for invalid input, disable a button for an incomplete form, share context and variables across many parts of the app, count how many times you have performed an action, tell whether you should render a modal or not… there are endless possibilities that are exactly the reason why frontend development is so exciting: the user input is a new dimension in your variable matrix.</p>
<p>A <em>stateful</em> component is a component that renders differently based on its state. An input component that renders an error message or is disabled is a good example. On the other hand, a <em>stateless</em> component is a plain static UI, but is still useful. Suppose you want to render your website footer. Instead of duplicating code left and right, you can develop it once and call it anywhere, pretty much like a function, generating one source of truth, best for maintainability and consistency.</p>
<h3 id="use-props-to-pass-data-to-a-children-component">Use Props to pass data to a children component</h3>
<p>Sometimes your component is not stateful but still depends on outside variables. Think about a template, for example. It has a recipe, a specific form, but with “gaps” that are dynamically filled (variables).</p>
<p>Properties, or props, are precisely a way to customize a component that should always behave the same but can accept different data. Think about your driving license: everyone has the same, they look the same, and their layout is the same, but the name, number, expiration date, and whatnot are different. Those are the props filling up the gaps.</p>
<p>In React, props are always passed from father to child. We saw already that componentization transforms your app into a huge tree of code, and the communication needs to be direct, and top-down (there are some exceptions like contexts, though).</p>
<p>While this can be annoying occasionally, it really gives predictability to your code. If a variable is such, it <em>must be</em> because it is like so in the parent. And hence you can trace back that value to its origin, helping to debug a lot.</p>
<p>I remember my old days working on CakePHP where I would spend hours trying to decipher where that variable had come from. It was hard because communication wasn’t direct, top-down. It was buried somehow in contexts and controllers. Call it pragmatic, but it will make your life easier.</p>
<h3 id="use-different-component-patterns">Use different component patterns</h3>
<p>As always, there is never one single way to tackle a problem. Before hooks took off on the 16th version of React, there was a famous React pattern called <a href="https://reactjs.org/docs/higher-order-components.html" rel="noopener noreferrer" target="_blank"><strong>HOC, or Higher-Order Components</strong></a>.</p>
<p>In this pattern, you encapsulate a particular component with another one, like a sandwich. But this gives it superpowers, or in less exciting terms, new props for it to use. For example, you could wrap your component in a HOC that would monitor the screen size in order to pass to your child component the width and height as props.</p>
<p>In some sense, Higher-Order Components worked as <em>decorators</em>, injecting logic into a given component. As mentioned, though, React Hooks was a great breakthrough and replaced this behavior with a nicer, more reusable API. Hooks work similarly to plugins, where you call them in your component to get a specific behavior.</p>
<p>Also before hooks, React components would be class-based, bringing more of the objected-oriented world to the frontend community. They would provide lifecycle hooks instead, where you could act when a specific event occurred, like the component mounting, or a specific prop changing.</p>
<p>The React team replaced this paradigm with a new one, using hooks, called <a href="https://reactjs.org/docs/hooks-effect.html" rel="noopener noreferrer" target="_blank"><strong>useEffect</strong></a>. Now, you can monitor everything that makes a component re-render, the act of being updated because something in the tree changed. It’s up to you to monitor and act accordingly to whatever state or prop change happened.</p>
<p>While more flexible, arguably some developers miss the straightness of <em>componentDidMount</em> or <em>componentWillUpdate</em>. If that’s who you are, you should check class-based components.</p>
<h2 id="styling"><strong>Styling</strong></h2>
<p>A hot topic with a myriad of alternatives, styling a web app is never a consensus. Constructed on top of a controversial piece of technology, we shall explore how you can approach styling in your React applications.</p>
<h3 id="try-inline-css">Try inline CSS</h3>
<p>The simples solution, by and large, is to embrace tradition and use an inline style like everyone was doing with HTML in the 90s. There’s nothing really wrong with it – with the exception that is hard to reuse.</p>
<p>React will handle style pretty much like a JSON object, and this will be the source behind the multiple CSS-in-JS frameworks that emerged. In any case, inline CSS is good, simple, and efficient. They will lack performance improvements (like being able to cache a separate CSS file), and maybe software engineering best practices. But they will work just fine.</p>
<h3 id="import-styled-components-as-an-object">Import styled-components as an object</h3>
<p>Using JavaScript to style your components has the unbeatable advantage of being able to control the style dynamically. Suppose you are building a component that changes its color based on a given input. JavaScript and React will make your life a breeze because you can just conditionally use the input to render the desired color.</p>
<p>Of course, people wouldn’t stop there: if you can use JavaScript in such cases, you can also use them to control other aspects of your styling. For example, font size, brand colors, default line height, etc. Using technology like <a href="https://www.styled-components.com/" rel="noopener noreferrer" target="_blank"><strong>styled-components</strong></a> allows you to write CSS-in-JS while creating a hierarchy of values that programmers so often like.</p>
<p>And as I mentioned before, the <em>style</em> property is nothing more than a JSON object. So you can leverage JavaScript constants to build your style schema, inherit from it, and write your component’s style as you would write code. Neat.</p>
<h3 id="abstract-style-components">Abstract style components</h3>
<p>Styles are good and a simple solution, but as a project grows it won’t scale. Think about how many primary buttons you have in your application and you will know what I mean.</p>
<p>As I mentioned in the previous section, styled-components help you to create a basic structure and build from there, with basic properties being set as constants. You can then combine them and create more complex structures, like buttons, paragraphs, headers, heroes, inputs, and so on.</p>
<p>In fact, React creates the perfect ecosystem for you to design your own component library. Forget about Bootstrap, Semantic UI, and their peers – with React, you please any designer you work with consistency and accuracy.</p>
<h3 id="use-css-and-sass-stylesheets">Use CSS and SASS stylesheets</h3>
<p>Everything I said thus far is great but some freaks insist on using plain old CSS files. Why? Well, I can tell (I’m one of those freaks). CSS is a technique on its own, and I prefer the separation of concerns of having a file dedicated to styling. It’s easier to review, change and adapt. Also, it can be cached when performance is at stake.</p>
<p>With the surge of frameworks that allow CSS Modules, the typical problem of classes clashing with each other is over. Plus, it generates a fingerprint that helps developers debug by targeting the precise component with that particular style.</p>
<p>And if you want the option to add parameters to your classes, like a brand color or semantic font size, SASS can help you. Pair both and you will get the best of two worlds, while still looking cool by using a time-tested fool-proof technology like cascading stylesheets.</p>
<h2 id="project-structure"><strong>Project structure</strong></h2>
<p>React is definitely not an opinionated library. As Uncle Ben would recall, “with great powers come great responsibilities”. I would also say, in a poetic tone, that you are free to do whatever you want, but a prisoner of the consequences.</p>
<p>With that in mind, let us take a look at how you can structure your React project.</p>
<h3 id="split-components-into-separate-tsx-files">Split components into separate .tsx files</h3>
<p>We already mentioned the power of componentization and treating components as you would treat functions in a functional paradigm. But in React this is even better if you enforce that only one component should exist per file.</p>
<p>First, files become smaller, and easier to tweak and review. Secondly, the <em>separation of concerns</em> buzzword rings again. By having a single file handling a single part, it’s very easy to spot and tackle eventual changes. Finally, if working on a larger team, will reduce conflicts and make collaboration a breeze.</p>
<h3 id="give-each-component-single-responsibilities">Give each component single responsibilities</h3>
<p>I’m a big fan of small, self-contained files, functions, and components. Think of them as small building blocks that are combined and used to create something bigger, like the pyramids, or a computer processor.</p>
<p>By assigning single responsibilities to each component, you are essentially functioning as a factory, with ultra-specialized employees that handle one thing and that thing only. Therefore, if <em>X</em> goes south, you know immediately that you need to talk with the one responsible for <em>X</em>. If each component has a single responsibility, it follows that it must exist only one component for it.</p>
<p>Combine multiple components with single responsibilities and you get your own production line.</p>
<h3 id="group-files-by-structures-or-routes">Group files by structures or routes</h3>
<p>We have already learned that React won’t enforce any file structure. Some people will circumvent this freedom but enforcing their own strict rules. I disagree. I believe React is better experienced if you leverage this freedom.</p>
<p>I explain: a successful folder structure is one you don’t need to think about. Frankly, the less you need to think about those petty things, the better. On that note, I like to group files <em>semantically</em>, or when they belong to a specific chunk of the app.</p>
<p>Have a route that renders a specific view? Add all your components there. Created a new page? Create also a new folder and add the corresponding components there as well. Simples structure. Not much thought is needed.</p>
<p>I oftentimes see people trying to be smart and breaking down components in multiple folders, with technical characteristics attached to them, like calling them <em>atomic</em>. I don’t like it. This means creating a new file or folder is no longer a no-brainer, and should be actively reviewed at the expense of having inconsistent file structures across the board. If you don’t care about the inconsistencies, then why create a rule in the first place? Moreover, you really don’t gain much (if anything) by adding a custom file structure to your projects. Developers aren’t supposed to be navigating in folders anyway. Components are small and self-contained, which means you potentially have a lot of files, so what’s the use of manually looking for them? Hence my proposal: group files by routes or pages, and forget about it.</p>
<h3 id="avoid-too-much-nesting">Avoid too much nesting</h3>
<p>React is a big tree of components as discussed, and this is fine. However, if you are nesting too much, you probably are doing it wrong.</p>
<p>There are so many levels that you can descend. You have a list, a CRUD, a modal… you can’t nest forever. If possible, favor the horizontal spread of components, in its own routes, shallow enough that you are not lost in the abstraction and easy enough for a developer to find his or her way through the code.</p>
<h2 id="using-react-with-a-headless-cms"><strong>Using React with a headless CMS</strong></h2>
<p>React is a library for building user interfaces, as we have seen. But it has some interesting integrations. For example, you might want to have your app’s content set somewhere else but render it in your shiny, fast, and efficient React app.</p>
<p>For such cases, content management systems like ButterCMS are a breeze. I spoke already about the separation of concerns, but this isn’t only related to code. In fact, the more you can separate areas of expertise, leaving people to their bread and butter, the better.</p>
<p>If you have a team of content creators, you can give them the freedom to put their creativity to work, generating content that will later be consumed and rendered in your application. Your developers shouldn’t need to have additional work if content changes – the own project structure should be able to do it.</p>
<p>Connecting a CMS provider with a React framework like GatsbyJS will empower you to do exactly that – <a href="https://buttercms.com/blog/leveraging-gatsby-incremental-builds/" rel="noopener noreferrer" target="_blank"><strong>connect to the content being generated, listen to changes, and rebuild your site with fresh content</strong></a>.</p>
<p>Server-side rendering applications like NextJS will also be valuable by fetching data from the CMS and serving to the user as requested.</p>
<p>In short, the JavaScript ecosystem for content management has evolved to the point where having blazing-fast, <a href="https://buttercms.com/blog/react-seo-how-to-build-search-friendly-pages-in-react/" rel="noopener noreferrer" target="_blank"><strong>SEO-friendly web apps</strong></a> can be achieved with both great content and developer experiences.</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[React SEO: How to Build Search-Friendly Pages in React]]></title>
<description><![CDATA[How to boost your React app SEO ranking with many practical tips.]]></description>
<link>https://rafaelquintanilha.com/react-seo-how-to-build-search-friendly-pages-in-react/</link>
<guid isPermaLink="false">6383abfb14168e003dd8f748</guid>
<category><![CDATA[React]]></category><category><![CDATA[SEO]]></category><category><![CDATA[Best Practices]]></category><category><![CDATA[ButterCMS]]></category>
<dc:creator><![CDATA[Rafael Quintanilha]]></dc:creator>
<pubDate>Thu, 21 Jan 2021 18:27:00 GMT</pubDate>

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

<content:encoded><![CDATA[<figure class="image"><img alt="Writing tests as user stories" loading="lazy" decoding="async" width="730" height="412" src="https://rafaelquintanilha.com/_astro/cover.C8BHRagE_ZXhSWk.webp"><figcaption>Writing tests as user stories</figcaption></figure>
<p>Testing code can be a controversial subject, largely due to the multitude of ways one can go about writing a test.</p>
<p>There are no clear rules, and ultimately you are the one in charge of deciding what’s worth testing and how you’re going to do it.</p>
<p>One common mistake is to test implementation details, but perhaps you’ve read that already.</p>
<p>Let me take a step back then — what is the end goal of a test?</p>
<h2 id="writing-user-stories">Writing user stories</h2>
<p>A common software abstraction is to write user stories — that is, possible actions that a user can take when interacting with your application.</p>
<p>Suppose you are to build a Celsius-to-Fahrenheit converter. A legitimate story could be something like:</p>
<p><em>“As a user, I want to be able to convert from Celsius to Fahrenheit.”</em></p>
<p>Naturally, as a careful developer, you want to assert that for a given set of numbers and inputs the conversion works (or it fails gracefully for invalid inputs like “banana”).</p>
<p>Note, however, that testing that a function is able to successfully handle the conversion from Celsius to Fahrenheit is only half the story.</p>
<p>If you are able to perform the most expensive and relevant calculation but your end user can’t access it, all effort will be in vain.</p>
<p>Why is that?</p>
<p>Well, as a frontend developer, your job is to not only ensure users get the correct answers to their questions but also to make sure they can use your application.</p>
<p>Therefore, you need to assess that the user has interacted with your application as expected.</p>
<p>In our example, that means that somewhere on the screen you expect some text to be displayed like this: “25ºC equals 77ºF.”</p>
<p>Now, that’s a relevant test. You just assessed that, for a given input, the user satisfactorily got the right answer on the screen.</p>
<h2 id="stories-mostly-dont-care-about-details">Stories (mostly) don’t care about details</h2>
<p>The main takeaway here is that the user stories aren’t centered on your development implementations, so your tests shouldn’t be, either.</p>
<p>Of course, the scenarios in question are related to application-wide tests (things that have context), not bare-bones libraries.</p>
<p>If your goal is to create a library that converts Celsius to Fahrenheit to Kelvin, then it’s fine to test the details once you are detached of context.</p>
<p>Now that we understand that tests should resemble user stories, you can predict where semantics come from.</p>
<p>At the end of the day, your tests should have clear semantics such that you could read them in plain English—the same way you describe user stories.</p>
<p>We’ll see how we can leverage the <a href="https://github.com/testing-library/react-testing-library" rel="noopener noreferrer" target="_blank">React Testing Library API</a> to write semantic tests that make sense.</p>
<h2 id="case-study-temperature-converter">Case study: Temperature Converter</h2>
<p>Let’s dive further into the Temperature Converter application.</p>
<p>We’ll pretend that a competent Project Manager heard the complaints of their clients (probably any non-American who has moved recently to the US) and came up with the following requirements:</p>
<ul>
<li>As a user, I want to be able to convert from Celsius to Fahrenheit</li>
<li>As a user, I want to be able to convert from Fahrenheit to Celsius</li>
<li>As a user, I want to click on a Reset button so I can easily convert many values with minimal effort</li>
</ul>
<p>Apart from the lack of creativity of the PM when writing stories, the requirements are pretty straightforward.</p>
<p>We will sketch a simple app, do a good ol’ smoke test to check that everything looks alright, and then apply what we just learned in order to write better tests.</p>
<p>Consider the following CodeSandbox for our sample application:
<a href="https://codesandbox.io/s/temperature-converter-mw7se" rel="noopener noreferrer" target="_blank">https://codesandbox.io/s/temperature-converter-mw7se</a></p>
<p>Diving into the specifics of the code is beyond the scope of this article (check <a href="https://rafaelquintanilha.com/how-to-reuse-logic-with-react-hooks">“How to Reuse Logic With React Hooks</a>” for more context on how to use Hooks to create React applications).</p>
<p>However, the code should be pretty straightforward. We are basically requiring user input and allowing them to convert from Celsius to Fahrenheit or vice-versa.</p>
<p>We then display the results and a Reset button shows up. Upon clicking the button, the input is cleared and regains focus.</p>
<p>This aligns with what our users are looking for: we’ll improve the usability of the app and, most importantly, preserve its accessibility.</p>
<p>Now that we have a live application that seems to work, let’s be responsible developers and write some tests.</p>
<p>We’ll try to match each user story to a single test. By doing that, we will be confident that each requirement is being fulfilled with a set of tests backing us up.</p>
<p>Consider this basic skeleton for <code>App.test.js</code>:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> React </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'react'</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> { cleanup } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> '@testing-library/react'</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">afterEach</span><span style="color:#ECEBE8">(cleanup)</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">test</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'user is able to convert from celsius to fahrenheit'</span><span style="color:#ECEBE8">, () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">  /* story 1 goes here */</span></span>
<span class="line"><span style="color:#ECEBE8">})</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">test</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'user is able to convert from fahrenheit to celsius'</span><span style="color:#ECEBE8">, () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">  /* story 2 goes here */</span></span>
<span class="line"><span style="color:#ECEBE8">})</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">test</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'user can reset calculation and automatically focus on the input'</span><span style="color:#ECEBE8">, () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">  /* story 3 goes here */</span></span>
<span class="line"><span style="color:#ECEBE8">})</span></span></code></pre></figure>
<p>(We are using <a href="https://jestjs.io/" rel="noopener noreferrer" target="_blank">Jest</a> as our test runner, but that’s not relevant to the main point presented in the article.)</p>
<p>Notice that our three tests are really straightforward and any failures in them would quickly expose what is really going on.</p>
<p>Now we’ll leverage RTL and write the first test in a way that makes sense:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> React </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'react'</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> App </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> './App.js'</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> { cleanup, render, screen } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> '@testing-library/react'</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> userEvent </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> '@testing-library/user-event'</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">afterEach</span><span style="color:#ECEBE8">(cleanup)</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">test</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'user is able to convert from celsius to fahrenheit'</span><span style="color:#ECEBE8">, () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#EDCC95">  render</span><span style="color:#ECEBE8">(&#x3C;</span><span style="color:#A1C1E4">App</span><span style="color:#ECEBE8"> />)</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> input </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> screen.getByLabelText</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'Temperature:'</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#EDCC95">  userEvent.type</span><span style="color:#ECEBE8">(input, </span><span style="color:#97CCAE">'25'</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#EDCC95">  expect</span><span style="color:#ECEBE8">(</span><span style="color:#EDCC95">screen.getByText</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'25ºC equals to 77ºF'</span><span style="color:#ECEBE8">))</span><span style="color:#EDCC95">.toBeTruthy</span><span style="color:#ECEBE8">()</span></span>
<span class="line"><span style="color:#EDCC95">  userEvent.type</span><span style="color:#ECEBE8">(input, </span><span style="color:#97CCAE">'0'</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#EDCC95">  expect</span><span style="color:#ECEBE8">(</span><span style="color:#EDCC95">screen.getByText</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'0ºC equals to 32ºF'</span><span style="color:#ECEBE8">))</span><span style="color:#EDCC95">.toBeTruthy</span><span style="color:#ECEBE8">()</span></span>
<span class="line"><span style="color:#EDCC95">  userEvent.type</span><span style="color:#ECEBE8">(input, </span><span style="color:#97CCAE">'banana'</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#EDCC95">  expect</span><span style="color:#ECEBE8">(</span><span style="color:#EDCC95">screen.queryByTestId</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'result'</span><span style="color:#ECEBE8">))</span><span style="color:#EDCC95">.toBeFalsy</span><span style="color:#ECEBE8">()</span></span>
<span class="line"><span style="color:#ECEBE8">})</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">/* code goes on */</span></span></code></pre></figure>
<p>There are a couple of things to notice with the dependencies:</p>
<p>First, we import the component in question <code>App.js</code>.</p>
<p>Then, notice that we are importing <code>render</code> and <code>screen</code> from RTL. While the first has been around since the library’s first launch, <code>screen</code> is a new addition <a href="https://github.com/testing-library/react-testing-library/releases/tag/v9.4.0" rel="noopener noreferrer" target="_blank">shipped on version 9.4.0</a>. We will see its main advantage shortly.</p>
<p>We also import a new dependency, <a href="https://github.com/testing-library/user-event" rel="noopener noreferrer" target="_blank">userEvents</a>, straight from <code>@testing-library/user-event</code>. This library will boost our test readability and help us achieve our goal of improving our semantics.</p>
<p>Let’s actually dive into the test. If you are used to RTL, the first thing you’ll notice is that <code>render</code> is not returning anything. In fact, that’s the main advantage of importing <code>screen</code>.</p>
<p>What <code>screen</code> does is basically expose all queries that allow you to select elements in the screen (hence the name).</p>
<p>This is a pretty good change because it helps you avoid bloating the test with lots of <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment" rel="noopener noreferrer" target="_blank">destructuring</a>, which is always annoying when you are not sure yet which queries to use.</p>
<p>Also, the code looks cleaner. (Note: there’s still a case for de-structuring <code>container</code> and <code>rerender</code> as mentioned by Kent C. Dodds <a href="https://twitter.com/kentcdodds/status/1224790664354779136" rel="noopener noreferrer" target="_blank">in this tweet</a>.)</p>
<p>The other difference from conventional tests you might have been writing is the <code>userEvent</code> object.</p>
<p>This object provides a handful of user interactions that are semantically understandable and conceal implementation details. Consider the following example:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A7A49E;font-style:italic">// Previously</span></span>
<span class="line"><span style="color:#EDCC95">fireEvent.change</span><span style="color:#ECEBE8">(input, { target: { value: </span><span style="color:#97CCAE">'25'</span><span style="color:#ECEBE8"> } })</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">// With userEvents</span></span>
<span class="line"><span style="color:#EDCC95">userEvent.type</span><span style="color:#ECEBE8">(input, </span><span style="color:#97CCAE">'25'</span><span style="color:#ECEBE8">)</span></span></code></pre></figure>
<p>Not only is our code is shorter, but it also makes much more sense now.</p>
<p>Remember that our goal is to write a test as close as possible to plain English. By encapsulating implementation details, <code>userEvent</code> really puts us on the right track.</p>
<p>If you are curious, <a href="https://github.com/testing-library/user-event" rel="noopener noreferrer" target="_blank">go ahead and check their documentation</a>.</p>
<p>Once we are able to fill the input, we can now assert that the correct text is being displayed.</p>
<p>Now we can test a bunch of other options and confirm that what is displayed in the screen is expected (e.g., an invalid input like <code>banana</code> won’t work).</p>
<p>Note: in a modular application, the conversion functions could be extracted in their own file and have their own tests (with many more test scenarios).</p>
<p>If you test the function separately, there’s no need to make redundant checks in the user stories as well (test is code and you want it maintainable as such).</p>
<p>With a test that is only eight lines long, we were able to check that our first scenario works as expected.</p>
<p>Let’s jump into our second user story — convert from Fahrenheit to Celsius (maybe a New Yorker having some fun on a beach in South America).</p>
<p>The test should be pretty similar to our first one, with a single caveat: we need to make sure that the user has selected the right option.</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#EDCC95">test</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'user is able to convert from fahrenheit to celsius'</span><span style="color:#ECEBE8">, () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#EDCC95">  render</span><span style="color:#ECEBE8">(&#x3C;</span><span style="color:#A1C1E4">App</span><span style="color:#ECEBE8"> />)</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> fahrenheitOption </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> screen.getByLabelText</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'Fahrenheit to Celsius'</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#EDCC95">  userEvent.click</span><span style="color:#ECEBE8">(fahrenheitOption)</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> input </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> screen.getByLabelText</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'Temperature:'</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#EDCC95">  userEvent.type</span><span style="color:#ECEBE8">(input, </span><span style="color:#97CCAE">'77'</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#EDCC95">  expect</span><span style="color:#ECEBE8">(</span><span style="color:#EDCC95">screen.getByText</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'77ºF equals to 25ºC'</span><span style="color:#ECEBE8">))</span><span style="color:#EDCC95">.toBeTruthy</span><span style="color:#ECEBE8">()</span></span>
<span class="line"><span style="color:#EDCC95">  userEvent.type</span><span style="color:#ECEBE8">(input, </span><span style="color:#97CCAE">'32'</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#EDCC95">  expect</span><span style="color:#ECEBE8">(</span><span style="color:#EDCC95">screen.getByText</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'32ºF equals to 0ºC'</span><span style="color:#ECEBE8">))</span><span style="color:#EDCC95">.toBeTruthy</span><span style="color:#ECEBE8">()</span></span>
<span class="line"><span style="color:#EDCC95">  userEvent.type</span><span style="color:#ECEBE8">(input, </span><span style="color:#97CCAE">'banana'</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#EDCC95">  expect</span><span style="color:#ECEBE8">(</span><span style="color:#EDCC95">screen.queryByTestId</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'result'</span><span style="color:#ECEBE8">))</span><span style="color:#EDCC95">.toBeFalsy</span><span style="color:#ECEBE8">()</span></span>
<span class="line"><span style="color:#ECEBE8">})</span></span></code></pre></figure>
<p>That’s it. By leveraging <code>userEvent</code> again, emulating a click event becomes trivial.</p>
<p>Our code is perfectly readable and guarantees that the reverse direction (F to C) works as expected.</p>
<p>Our third and final test is slightly different — now our goal is to test the user experience rather than whether or calculator works.</p>
<p>We want to make sure that our application is accessible and that users can rapidly test several values:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#EDCC95">test</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'user can reset calculation and automatically focus on the input'</span><span style="color:#ECEBE8">, () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#EDCC95">  render</span><span style="color:#ECEBE8">(&#x3C;</span><span style="color:#A1C1E4">App</span><span style="color:#ECEBE8"> />)</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> input </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> screen.getByLabelText</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'Temperature:'</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#EDCC95">  userEvent.type</span><span style="color:#ECEBE8">(input, </span><span style="color:#97CCAE">'25'</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#EDCC95">  expect</span><span style="color:#ECEBE8">(</span><span style="color:#EDCC95">screen.queryByTestId</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'result'</span><span style="color:#ECEBE8">))</span><span style="color:#EDCC95">.toBeTruthy</span><span style="color:#ECEBE8">()</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> resetButton </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> screen.getByText</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'Reset'</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#EDCC95">  userEvent.click</span><span style="color:#ECEBE8">(resetButton)</span></span>
<span class="line"><span style="color:#EDCC95">  expect</span><span style="color:#ECEBE8">(</span><span style="color:#EDCC95">screen.queryByTestId</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'result'</span><span style="color:#ECEBE8">))</span><span style="color:#EDCC95">.toBeFalsy</span><span style="color:#ECEBE8">()</span></span>
<span class="line"><span style="color:#EDCC95">  expect</span><span style="color:#ECEBE8">(document.activeElement)</span><span style="color:#EDCC95">.toBe</span><span style="color:#ECEBE8">(input)</span></span>
<span class="line"><span style="color:#ECEBE8">})</span></span></code></pre></figure>
<p>There you have it. We basically made three checks:</p>
<ul>
<li>Whenever a user adds some input, there’s a result displayed (the actual message shown is omitted from the test once this isn’t what is being checked here)</li>
<li>When the Reset button is clicked, the result is not there anymore</li>
<li>The focus on the screen is back to the input</li>
</ul>
<p>One of my favorite things about RTL is how easy it is to assert where a focus really is.</p>
<p>Notice how semantic <code>expect(document.activeElement).toBe(input)</code> is. That pretty much looks like plain English to me.</p>
<p>And that’s it. Our three stories are covered, the Project Manager is happier, and hopefully our tests will keep the code clean for a long time.</p>
<h2 id="conclusion">Conclusion</h2>
<p>The aim of this article was to expose the recent modifications in the React Testing Library’s API and show you how you can explore it to write better tests for you and your team.</p>
<p>I feel way more confident when I write tests that I understand because I stop chasing meaningless metrics (e.g. code coverage) to pay attention to what really matters (e.g. if my designed scenario works as expected).</p>
<p>React Testing Library was a big step in the right direction, mainly if you have some Enzyme background (in which case you might want to check “<a href="https://rafaelquintanilha.com/react-testing-library-common-scenarios/">React Testing Library Common Scenarios</a>,” where I explore how you tackle everyday scenarios in a React application).</p>
<p>It really facilitates testing what your application should do rather than how it does it. The semantics make a difference.</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[How to Become a Bad Developer]]></title>
<description><![CDATA[Discover the most efficient way to not succeed as a developer.]]></description>
<link>https://rafaelquintanilha.com/how-to-become-a-bad-developer/</link>
<guid isPermaLink="false">637056c142a473003d9dcad6</guid>
<category><![CDATA[Best Practices]]></category>
<dc:creator><![CDATA[Rafael Quintanilha]]></dc:creator>
<pubDate>Wed, 03 Jul 2019 03:00:00 GMT</pubDate>

<content:encoded><![CDATA[<p>The great mathematician Carl Jacobi once said <em>"Invert, always invert"</em>. He advocated that, by analyzing a problem backward, one could uncover the best solution to it.</p>
<p>With that in mind, Berkshire Hathway's legendary partner Charles Munger gave a <a href="http://jameslau88.com/charlie_munger_on_invert_always_invert.htm" rel="noopener noreferrer" target="_blank">terrific speech to the Harvard School</a> on how to <em>not</em> be successful (I originally read this and other Charles' speeches in the amazing <a href="https://www.amazon.com/gp/product/1578645018/ref=as_li_tl?ie=UTF8&#x26;tag=rafaelquintan-20&#x26;camp=1789&#x26;creative=9325&#x26;linkCode=as2&#x26;creativeASIN=1578645018&#x26;linkId=e16372c9ef26ae70461b9916a8a7b3de" rel="noopener noreferrer" target="_blank">Poor Charlie's Almanack: The Wit and Wisdom of Charles T. Munger</a>). That made me think – what is the easiest way to become a <em>bad</em> developer?</p>
<p>What you will see next is a highly subjective, non-exhaustive unordered list of principles that, if you follow, I can guarantee will lead you to become a bad developer. I say "principles" because I am not interested in technicalities (e.g. choose bad variable names, never comment on your code, etc), once they are a sub-product of the guidelines you follow.</p>
<p>If your goal, fellow reader, is to become a good developer instead, don't worry. Remember that <em>via negativa</em> is way more powerful than <em>via positiva</em>. That means that knowing what <strong>not</strong> to do is safer and easier to figure out than exactly what to do. So pay attention to the following topics and decide which type of developer you want to be.</p>
<h2 id="never-assume-there-is-a-bug-in-your-code">Never assume there is a bug in your code</h2>
<blockquote>
<p>“Vanity, definitely my favorite sin.” - Al Pacino, Devil's Advocate</p>
</blockquote>
<p>Software Development is one of the few areas where you have a free pass to make mistakes frequently. This is a very good spot to be if the impact of the mistakes is minimal.</p>
<p>Yet, it is easy to forget that. You can be the best developer in your company and <em>comparatively</em> make fewer mistakes than the others. But the <em>absolute</em> number of mistakes you make will still be high, there's no escape from it. The good news is that's fine – machines need a lot of precision when communicating and <strong>one bad sentence is enough to blow up a 10,000 LOC codebase</strong>.</p>
<p>But because you consider yourself better than the other developers, which might very well be true, you start to think that you don't make mistakes. Or that if some issue arose, you have nothing to do with it.</p>
<p>The problem is that many times you will have responsibility. Doesn't matter if you were the author of the bad code, overlooked it in your review process or didn't anticipate it when planning. <strong>There are just too many ways of making mistakes</strong>.</p>
<p>So if you never assume that you might have blown things up, you will start blaming other things – your peers, the stupid framework you are using, an outdated browser or a pre-historic OS. Anything will be responsible but you. And if you never admit your mistakes, you are cursed to never evolve. And not evolving as a developer is fatal.</p>
<h2 id="write-code-without-reasoning">Write code without reasoning</h2>
<blockquote>
<p>The truth can be perceived only through thinking. - Thomas Aquinas</p>
</blockquote>
<p>One of the first things that we learn as humans belonging to societies is that we need to measure the consequences of our acts. The same applies to programming. Ultimately, your job is to create value for people through lines of code. If you lose track of this, you have become a bureaucrat. And well, it's pretty hard for a bureaucrat to be a good developer.</p>
<p><strong>If you act without thinking, you are wasting the very edge that you have over machines</strong>. You are a candidate to be replaced in the near future (either by a thoughtful human or by a cheaper dumb machine). Always try to understand what's the purpose of the task you've been assigned to. Unless, of course, you want to become a bad developer.</p>
<h2 id="lack-assertiveness">Lack assertiveness</h2>
<blockquote>
<p>Control your own destiny or someone else will. - Jack Welch</p>
</blockquote>
<p>I am yet to find a good developer who is unable to report the issues he or she is facing with clarity of mind.  This happens because computers are very obedient entities which only function when given precise instructions. If you are assertive when debugging your code, chances are you will figure out the problem by yourself. But even if you don't, you are halfway through the solution and a fresh pair of eyes will be much more effective in the process of helping you.</p>
<p>Remember that machines are very dumb and need to be correctly told what to do. And that you give them too many instructions during your work. Eventually, you will give the wrong instructions. If you can't effectively walk through your code and identify the misplaced directives, you will be a bad developer.</p>
<h2 id="take-pleasure-in-writing-more-code">Take pleasure in writing more code</h2>
<blockquote>
<p>“Until we have begun to go without them, we fail to realise how unnecessary many things are. We've been using them not because we needed them but because we had them.” -  Seneca</p>
</blockquote>
<p>It is very common, especially among novice developers, to be proud of the number of lines of code their application has. This is, indeed, a very strong sign that you are in good shape to become a bad developer.</p>
<p>Every line of code is an instruction to a machine. <strong>The greater the number of instructions, the greater the number of mistakes are there to be made</strong>. It also means that you will need more knowledge if you ever want to change how your code behaves. By writing as many lines as possible, you are shielding people from your work. A code that nobody wants to read and many fear touching is a bad code.</p>
<p>I've mentioned <em>via negativa</em> before. Simply put, it means "the less, the better". The reasoning is as follows: <strong>there are many more ways to screw things up than to improve them</strong>. Someone who wants no trouble will focus on minimizing the probability of screwing the codebase, whereas a bad developer will actively look for more additions.</p>
<p>Recall that every line of code will eventually be read, tested, changed, incremented or even deleted. It's pretty clear that your workload is proportional to the amount of code. Someone who increases his or her workload unnecessarily is just a bad developer.</p>
<h2 id="write-for-machines-not-humans">Write for machines, not humans</h2>
<blockquote>
<p>“It has become appallingly obvious that our technology has exceeded our humanity.” - Albert Einstein.</p>
</blockquote>
<p>Finally, this is the most efficient way to achieve your goal of being a bad developer. I say that because writing code for machines instead of humans is the easiest of all the bad things you can do. It's terribly simple to write undocumented code, use inaccurate variable names, be inconsistent, forget about indentation, and so on.</p>
<p>You need to recall that <strong>machines understand machine code</strong>. All other things that are not 1's and 0's are just ornament to make code more readable to humans. If you don't pay attention to this, you are making humans' lives harder – thus, a perfect way to be a bad developer.</p>
<p>Think about what makes a text enjoyable to you. It is usually concise, clear, direct, meaningful and consistent. You won't enjoy reading when you can't understand the author, the narrative doesn't make sense, it's poorly written or weirdly formatted. Likewise, code that does not make sense and that you need to strive to grasp is an excellent form of discouraging the reader. And the same way an author who discourages their readers is a bad author, a developer who discourages their readers is a bad developer.</p>
<hr>
<p>I hope that you find the above rules useful in your quest of becoming a bad developer. But if you ever change your mind and decide to grow into a good one instead, well, you now know what you need to avoid.</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[How to Efficiently Go From Idea to Prototype in React]]></title>
<description><![CDATA[A guide for fast interface designs.]]></description>
<link>https://rafaelquintanilha.com/how-to-efficiently-go-from-idea-to-prototype-in-react/</link>
<guid isPermaLink="false">63703c1342a473003d9dc905</guid>
<category><![CDATA[React]]></category><category><![CDATA[Best Practices]]></category>
<dc:creator><![CDATA[Rafael Quintanilha]]></dc:creator>
<pubDate>Thu, 04 Apr 2019 03:00:00 GMT</pubDate>

<content:encoded><![CDATA[<p>It is not uncommon for a client to have only a fuzzy idea about an app. They might be only experimenting, with an incomplete business model and many times lacking technical background. As a CTO, being able to handle this situation can be a game-changer between a frustrated client and a successful product.</p>
<p>Software, during its conception, is a simple abstraction. You imagine what you would like to achieve, but you can’t do it until it comes to existence (at least partially). That’s why front-end work is really important - it bridges the gap between what your clients imagine to what they see.</p>
<p>By quickly presenting clients with something visual you can gather much more relevant feedback, avoid early pitfalls and significantly increase the likelihood of success. Besides, chances are your clients won’t care about magnificent back-end work, since they can’t see it directly! For non-technical people, the reality is that the UI will cause much more impact.</p>
<p>This article aims to provide you with a simple guide on how to efficiently prototype a front-end application using React. <strong>The information you will find here has been compiled during several years of consulting work and contains feedback from many clients</strong>.</p>
<h2 id="the-right-tools-for-the-job">The right tools for the job</h2>
<p>When seeking efficiency, it is mandatory to use the right tooling. This is not a debate of which technology or framework is better for your project, but rather what tools can increase your velocity <em>given</em> your stack’s choice (in our case, React).</p>
<h4 id="starters">Starters</h4>
<p>You don’t want to waste time optimizing your webpack or installing Babel plugins during this phase, so a good starter is recommended. There are many, but I’ll emphasize the following:</p>
<ul>
<li><a href="https://facebook.github.io/create-react-app/" rel="noopener noreferrer" target="_blank">create-react-app</a>: with a single command line, fire up a React application. It has drop-in functionalities but also the ability to change advanced settings. It is maintained by the React team, so you can expect continuous development and improvement. It is less opinionated, meaning that you still have to tweak it a bit (e.g. add routing).</li>
<li><a href="https://www.gatsbyjs.org/" rel="noopener noreferrer" target="_blank">GatsbyJS</a>: create blazing-fast apps with outstanding features like pre-fetching, code splitting, and offline support out-of-the-box. Comes with its own routing solution and uses GraphQL as an interface for fetching data.</li>
<li><a href="https://nextjs.org/" rel="noopener noreferrer" target="_blank">NextJS</a>: similar to Gatsby, but focused on server-side rendering, which means enhanced SEO capabilities (although you might not be much interested in that in a prototype) and universal rendering (JavaScript everywhere).</li>
</ul>
<p>The truth is that you will be fine with any of them. Personally, I like to use Gatsby when the project is front-end heavy (meaning a lot of static pages and few connections with the server). If I need more freedom to use the libraries I want, CRA would be my choice. Finally, if I’m more concerned about the back-end and willing to use JavaScript in there, NextJS is very suitable.</p>
<h4 id="deployment">Deployment</h4>
<p>One of the greatest advantages of doing front-end work is that deploying and sharing have become trivial. There are many free solutions that allow you to deploy your prototype in literally a couple of minutes.</p>
<p>You can achieve that with <a href="https://www.netlify.com/" rel="noopener noreferrer" target="_blank">Netlify</a>, <a href="https://nextjs.org/" rel="noopener noreferrer" target="_blank">Vercel</a> (formerly ZEIT) and <a href="https://surge.sh/" rel="noopener noreferrer" target="_blank">Surge</a> (among others). All of them will cover your back and provide HTTPS support, custom domains, and continuous development. Particularly, I’m very fond of Netlify and find their deployment process insanely trivial. Simply connect your GitHub or BitBucket account, push your code and wait a few seconds until your app is available on the internet.</p>
<p>The power of firing up a static website with a custom domain and sharing it with your clients is priceless. It is a good strategy to bring them close to the development, ask them for help to test multiple devices and as a consequence have them gather feedback and find bugs much earlier.</p>
<h2 id="the-very-beginning">The very beginning</h2>
<p>Now that you have decided on your starter and are able to deploy and share a “Hello World” with your client in 5 minutes, it is time to start designing your UI for your React app.</p>
<p>As a non-designer, my first instinct is to draft a rough version of the interface. This process helps me to turn something abstract into concrete.</p>
<p>Suppose your client wants to develop a resumé application, where users can fill in personal information, work experience, relevant skills, and educational background. Stop for a few minutes and try to picture this application in your head. How is every section displayed? Do you anticipate users will need to upload a photo? Have you ever seen software that does something <em>similar</em> to that? If that’s the case, what’s good about it?</p>
<p>Here’s what I came up with:</p>
<figure class="image"><img alt="Rough sketch" loading="lazy" decoding="async" width="504" height="683" src="https://rafaelquintanilha.com/_astro/rough-design.BoCZ4WAQ_Z1AUA7m.webp"><figcaption>Rough sketch</figcaption></figure>
<p>As you can see, I’m no Pablo Picasso. But that’s OK -- I’m not interested in the final design yet, just a base layout. Once I have that, I can start positioning HTML elements, adding some CSS, and getting some feedback.</p>
<h4 id="look-for-inspiration">Look for inspiration</h4>
<p>Having a starting point is good but you don’t want to showcase an app that looks like it was built in 1996. In order to give a little glamour to your sketch, you can start looking for inspiration.</p>
<p>As I already mentioned, a good way to start is to find out apps with similar features. In our example, <a href="https://www.linkedin.com/" rel="noopener noreferrer" target="_blank">LinkedIn</a> is certainly a match. Important: <em>you don’t want to make a copy</em>. But if your users can easily relate to the interface, it’s a win. Notice the styling trends. Details can really make a difference here: padding, font sizes, text and background colors, shadows, etc.</p>
<p>It’s also a good idea to search for particular UI designs. A good website for this is <a href="http://collectui.com" rel="noopener noreferrer" target="_blank">Collect UI</a>. While I don’t expect to come up with fancy animations, I do get a lot of good inspiration from their gallery.</p>
<figure class="image"><img alt="CollectUI as a source of inspiration" loading="lazy" decoding="async" width="2000" height="1250" src="https://rafaelquintanilha.com/_astro/collectui.DAoJN8ia_1sLvSI.webp"><figcaption>CollectUI as a source of inspiration</figcaption></figure>
<p>Finally, there are libs that provide a collection of common components such as buttons, form components, headers, etc. One of my favorites is <a href="https://react.semantic-ui.com/" rel="noopener noreferrer" target="_blank">Semantic UI React</a>, which is extensible and customizable. Picking a good collection can save you a lot of time.</p>
<h4 id="start-with-html-and-css">Start with HTML and CSS</h4>
<p>It’s time to convert the sketch and your inspirations into code. You are moving one step further in the concreteness of your app. What’s the best way of doing it?</p>
<p>The simpler way is to start with HTML and CSS only, even though you are using a React starter. Start laying DOM elements around, try different styles. Change the positioning, colors, borders. Aggregate related pieces of UI but don’t try to over-engineer yet: no need to start decomposing your UI into multiple React elements or caring about reusability. Surely, this will need to be done. But at this moment, free your mind from framework specifics and care about how your app should <em>look</em>.</p>
<p>During this phase, I avoid adding much interaction or special effects. If you envision a magnificent hover effect on the button or would like to dynamically add skills to your résumé, leave this aside for the moment.</p>
<p>Beware of 3rd party libraries that can add complexity - no need to install the awesome <a href="https://github.com/react-dropzone/react-dropzone" rel="noopener noreferrer" target="_blank">react-dropzone</a> package yet even though it would be cool to let users add new avatars at this point. First, chances are you still have a lot of loose ends - what if the avatar should be added to a “My Account” page? Or if the client requires the ability to crop the photo? What about different image extensions? Ultimately, now isn’t the right time. Second, prioritize: if you run out of time, would you rather have the full layout done with a placeholder avatar or a half-baked page that allows drag and drop?</p>
<h4 id="dont-be-careless">Don't be careless</h4>
<p>Most of my tips so far were pragmatic. You should focus on having a layout done and being able to share it with your client. Likely, your deadline is short (as with every deadline). You are tempted to create the first design it came to your mind, host it in Netlify and send the URL via email.</p>
<p><strong>Don’t do it.</strong></p>
<p>Although I sound contradictory, there’s a good reason for that: <em>you don’t want your job to be recognized as lazy or reckless</em>. It is very important to make a good first impression or you can frustrate your client. That doesn’t mean you need to redo your design ten times before asking for feedback - but bear in mind that you will be judged by the quality of your UI, even though you swear that “this is just a first draft and of course will be improved”.</p>
<p>When your design looks professional enough, so that when you compare to your inspirations it doesn’t look like it was done in a rush by an undergrad student, you are good to go.</p>
<h2 id="add-interactivity">Add interactivity</h2>
<p>At this point, you should have a better understanding of what your app needs to do. It’s time to transform this web page into a web app. Let the fun begin!</p>
<h4 id="low-hanging-fruits">Low-hanging fruits</h4>
<p>Start small. What features do your clients want that you can do in the shortest amount of time? Those are the ideal initial candidates.</p>
<p>In our sketch, there is a plus button on the right side of each section. Suppose one requirement is to dynamically add items into them. Well, React makes this kind of behavior pretty easy and it is hard to imagine the app without this feature. If your clients ever change their minds and want to add new items, say, through a modal window, you didn’t waste too much time.</p>
<h4 id="dont-show-off">Don’t show off</h4>
<p>JavaScript is arguably the most complex part of the development and that’s why you want to keep it under control. While you might have already envisioned fancy interactions for the software you are building, resist the temptation to “show off”.</p>
<p>First, you are in the realm where complex logic lives. If you make a misjudgment and a feature proves to be harder to implement than anticipated, you can get frustrated too soon and compromise the deadline.</p>
<p>Second, you don’t want to set a trap for yourself. Suppose that for each item in the sections you want to be able to delete them. How are you going to do it?</p>
<p>Surely, there are many ways. You can have a minus button that shows up on hover right after each item and removes it when clicked. You can also have a checkbox on the left side and a button to delete all marked items. What about being able to drag every item and drop them into a trash can?</p>
<p>None of the three options is necessarily <em>better</em> than the other. But you can easily identify the simpler one. The one that leaves less room for interpretation is preferred. In this example, where should the “Delete” button be? Are the checkboxes always visible? Is necessary to have a “Select All” option? For the drag-and-drop solution, what about mobile devices? Are you expected to support all OS? Where the trash can should be? Do you need a 3rd party library?</p>
<p>Make sure <em>you</em> are not the one who is adding complexity to the project.</p>
<h4 id="focus-on-the-happy-path">Focus on the happy path</h4>
<p>A real-world web application shouldn’t allow users to do whatever they want. For instance, if you are adding a new item to the Skills section, you certainly shouldn’t be able to add a 2,000-word essay.</p>
<p>Still, this kind of work can be cumbersome and less valuable. If your clients want to test the application and validate their views, adding a really long string as a skill item might not be a concern yet. They may not even realize that you are performing a validation!</p>
<p>It’s important that you define with your client the <em>happy path</em>, that is, the most common scenario that users fall into without anything unexpected happening. In our example, it can be the user going to their profile, populating every section with valid information and saving. This is a useful and testable scenario.</p>
<p>Leave the edge cases for later. Recall the <a href="https://en.wikipedia.org/wiki/Pareto_principle" rel="noopener noreferrer" target="_blank">Pareto Principle</a>, or the 80/20 rule: 80% of the scenarios are done with 20% of the work.</p>
<figure class="image"><img alt="Pareto Principle" loading="lazy" decoding="async" width="1024" height="507" src="https://rafaelquintanilha.com/_astro/pareto.BD5OrFMM_itYuF.webp"><figcaption>Pareto Principle</figcaption></figure>
<h2 id="decouple-the-ui-from-the-back-end">Decouple the UI from the back-end</h2>
<p>There is no doubt that back-end development is crucial for the success of your application. However, if your goal is to quickly prototype an interface, you can live without it.</p>
<p>The main reason is that most of the optimizations and improvements that the back-end brings are not very relevant at this stage. As mentioned before, it is likely that your clients don’t care much about you using the right ORM or automatically scaling in AWS. Again, that doesn’t mean they have no value - only that there are other things to focus on right now.</p>
<h4 id="separate-the-ui-from-the-api">Separate the UI from the API</h4>
<p>React is not very opinionated and therefore every developer is allowed to have their own preferences about how to split logic, create UI elements, manage side-effects, etc. Many patterns emerged from the community as a response to standardize procedures but in the end, this is your responsibility.</p>
<p>In the old days, people would talk about “Smart” and “Dumb” components. That evolved to the more politically correct terms “Stateful” and “Pure” or “Container” and “Presentational”. Ultimately, they all share the same goal: separate complex logic and stateful representations from what is UI only.</p>
<p>Why is that a thing? Well, “Presentational” components are much easier to implement. They are simple React components with little or no knowledge of the business logic, let alone API particularities. If you are building a dynamic list of skills, you certainly can start by developing the list and the items without minding too much if you are fetching this information from a REST API or a GraphQL server.</p>
<h4 id="hooks-are-your-friends">Hooks are your friends</h4>
<p><a href="https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0" rel="noopener noreferrer" target="_blank">There is a famous post from Dan Abramov</a> explaining his views about the topic above. However, the original post is from 2015 and <a href="https://reactjs.org/blog/2019/02/06/react-v16.8.0.html" rel="noopener noreferrer" target="_blank">just recently React launched official support for hooks</a>.</p>
<p>As mentioned in the article, hooks are another way of looking at the separation of concerns. Instead of reusing <em>components</em>, you can now reuse <em>logic</em>. This new paradigm speeds up development a <em>lot</em>. For example, suppose that your client requires some keyboard shortcuts such as pressing Ctrl + N to create a new item. You already have the UI for the items and likely an <code>addItem</code> function. In this case, all you need to do is <em>hook</em> the required logic into the UI. <a href="https://usehooks.com/useKeyPress/" rel="noopener noreferrer" target="_blank">useKeyPress</a> will then make your life a breeze.</p>
<h4 id="prepare-the-terrain-for-real-data">Prepare the terrain for real data</h4>
<p>If you successfully separate what is only UI from what is complex logic or API calls, the development process will become way smoother. That being the case, you can prepare your components for fetching data even if you don’t have an endpoint yet!</p>
<p>Assume you want to create an “Edit Profile” page for our sample application. This would involve fetching data from the API and filling in the corresponding fields. In terms of front-end development, you don’t need to wait for the back-end and database to be set to start working on it. Create a mock object which will mimic the response from the API (what makes designing the API extremely important) and feed it into your “Pure” or “Presentational” component.</p>
<p>If you need to persist data, e.g. be able to edit the profile, click on save and see the changes when you refresh the screen, experiment with the local storage. Although not recommended in production, it will work just fine for prototypes. If you are into hooks, there is a <a href="https://usehooks.com/useLocalStorage/" rel="noopener noreferrer" target="_blank">useLocalStorage</a> hook that trivializes this process.</p>
<p>When the time comes, succeeding at this phase will make switching to real data an effortless process.</p>
<h2 id="final-thoughts">Final thoughts</h2>
<p>All tips included in this article are a personal compilation of years of front-end development. This is not intended to be a final manual of some sort, but to provide guidance on how to efficiently handle clients' requests and keep project quality.</p>
<p>The main takeaways can be summarized in the following points:</p>
<ul>
<li><em>Communicate early</em>. The sooner you get feedback, the less time you will spend redoing work. This is somewhat expected when you are in the prototyping phase, so doing this efficiently will positively impact your velocity.</li>
<li><em>Avoid edge-cases</em>. Remember that you can cover 80% of the scenarios with 20% of the work. Do your clients a favor and have more meaningful features done in less time.</li>
<li><em>Don’t over-engineer</em>. Prototypes are fragile, likely to be modified and sometimes frustrating to develop. You don’t want to spend too much time abstracting just to find out that everything will change.</li>
<li><em>Design the API</em>. Clients will judge the interface first so you should put more effort into making it right. However, make sure you have a clear design of the API so, when it’s time, you can plug front-end and back-end seamlessly.</li>
</ul>]]></content:encoded>
</item>
</channel>
</rss>
