<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ilya Lyamkin on Medium]]></title>
        <description><![CDATA[Stories by Ilya Lyamkin on Medium]]></description>
        <link>https://medium.com/@ilyamkin?source=rss-67fde4696dbe------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*PJgUyo7Sao8CQauq2W-jJA.png</url>
            <title>Stories by Ilya Lyamkin on Medium</title>
            <link>https://medium.com/@ilyamkin?source=rss-67fde4696dbe------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 17:51:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ilyamkin/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[What Are Web Standards and How Do They Work With Web Browsers?]]></title>
            <link>https://medium.com/better-programming/what-are-web-standards-and-how-do-they-work-with-web-browsers-3876697920b1?source=rss-67fde4696dbe------2</link>
            <guid isPermaLink="false">https://medium.com/p/3876697920b1</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[chrome]]></category>
            <category><![CDATA[web-standards]]></category>
            <dc:creator><![CDATA[Ilya Lyamkin]]></dc:creator>
            <pubDate>Wed, 27 May 2020 12:22:15 GMT</pubDate>
            <atom:updated>2020-05-27T12:22:15.019Z</atom:updated>
            <content:encoded><![CDATA[<h4>A look inside your browser</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ka4gjlD99edNfUKl" /><figcaption>Photo by <a href="https://unsplash.com/@krstoj?utm_source=medium&amp;utm_medium=referral">Krsto Jevtic</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Let me tell you a story. I was building yet another date picker component for our design system. It consisted of text input and a pop-up calendar. The calendar can be closed by clicking outside it or by selecting a date.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vrAAS9RzZ-QB9I44VK31gQ.png" /><figcaption>Date picker component</figcaption></figure><p>Most implementations of the click outside logic are made with actual click listeners attached to the DOM. However, I wanted to make our date picker accessible, so you could open a calendar with tabs and close it the same way. Additionally, click listeners may conflict with each other if you put several date pickers on the page.</p><p>What if you could just rely on native focus and blur events instead of detecting clicks outside? They naturally support tabs, touch and click events, and are already implemented in the browser. The only problem is that when you click on the pop-up but do not select a date, focus shifts to the calendar, triggering a blur event on the text input and eventually closing the pop-up.</p><p>At this point, I started wondering if there was a way to click but not shift focus. After some quick googling, I found a way to do it: prevent the default action of the mouseDown event for the pop-up. Just like that, with one line of code, all the clicks worked but the focus was still on the text input.</p><p>It seemed like the solution, but I didn’t feel ready to move forward. Something inside me was stopping me. Why does specifically mouseDown and not mouseUp prevent focus but propagate a click? Is it some part of the living standards? Can we rely on that? Does it work cross-browser? The React Testing Library that we used to do integration tests also didn’t support it and I’d have to change the simulation function.</p><h3>What is a Web Standard?</h3><p>The Stack Overflow answer wasn’t enough for me, so where was there a better place to learn about browser behavior? Web standards.</p><p>You probably heard about <a href="https://www.w3.org/">W3C</a> or World Wide Web Consortium. It’s an international community that develops open standards for the Web. W3C makes sure that everyone follows the same guidelines and that we don’t have to support dozens of completely different environments. If you visit their website, you’ll find the list of <a href="https://www.w3.org/TR/">all the standards</a> they’re working on.</p><p>Let’s take a look at the one document that might have an answer to our questions — <a href="https://www.w3.org/TR/2019/WD-uievents-20190530/">UI Events Standard</a>. This specifies the DOM event flow and defines a list of events and their execution order. If you thought that standards are boring, obscure, and hard-to-understand text blocks, then jump straight to <a href="https://www.w3.org/TR/2019/WD-uievents-20190530/#dom-event-architecture">DOM Event Architecture</a> section. It explains event bubbling and capturing with nice pictures and still manages to be very specific, as standards must be. You’ll be surprised by the quality of it — it’s really well-written with many examples and recommendations.</p><p>It also has a definition of our mouseDown event and its default actions:</p><blockquote><em>“Many implementations use the </em><em>mouseDown event to begin a variety of contextually dependent default actions. These default actions can be prevented if this event is canceled. Some of these default actions could include: beginning a drag/drop interaction with an image or link, starting text selection, etc. Additionally, some implementations provide a mouse-driven panning feature that is activated when the middle mouse button is pressed at the time the </em><em>mouseDown event is dispatched.”</em></blockquote><p>OK, so our event has some default actions, but there’s nothing specific about focus because it really depends on browser implementations. Let’s check them out.</p><h3>Introduction to Browser Engines</h3><p>A modern browser is quite a complicated piece of software with a codebase of <a href="https://www.openhub.net/p/chrome/analyses/latest/languages_summary">tens of millions of lines of code</a>. So, it’s usually split into several parts.</p><p>To find a place where focus events are defined, we need to get an overview of each part and what it’s responsible for. Let’s start with Chromium and its design documentation, <a href="https://www.chromium.org/developers/how-tos/getting-around-the-chrome-source-code">Getting Around The Chrome Source Code</a>. As you can see, there are a lot of modules responsible for different areas of logic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CseGs3kjR-ngC6OjVj5_uw.png" /><figcaption>A high-level overview of Chromium</figcaption></figure><p>Let’s briefly go over them to get the idea of how it works together.</p><ul><li><strong>chrome: </strong>This is a base app with startup logic, UI, and all windows. It contains the projects for chrome.exe and chrome.dll . Resources such as icons or cursors you can also find here.</li><li><strong>content:</strong> This is a backend of the app which handles communication with child processes.</li><li><strong>net:</strong> This is the networking library that helps to make queries to websites.</li><li><strong>base:</strong> This is a place for common code shared between all sub-projects. This could include things like string manipulation, generic utilities, etc.</li><li><strong>blink: </strong>This is a rendering engine that responsible for the whole rendering pipeline including DOM trees, styles, events, V8 integration.</li><li><strong>v8:</strong> a final big part of a browser — Javascript engine. Its job is to compile JavaScript to native machine code.</li></ul><p>As you can see, a browser consists of several independent parts that talk to each other via API. The most interesting parts for developers are usually Blink and V8. Browser defined default actions are not part of V8, but Blink should have all of them defined and implemented. But before we jump into the Blink codebase, let’s understand how web browsers work from a user point of view.</p><h3>Rendering Pipeline</h3><p>Imagine you enter domain address in a browser, then it fetches and loads a bunch of assets: HTML, CSS, and JS files, images, icons. What happens next?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*84UIjX8jlBTcvmNtMeYk_w.png" /><figcaption>Web browser rendering pipeline</figcaption></figure><p>As a first step, HTML files are parsed and turned into a <em>DOM tree</em>. The DOM is not only the internal representation of the page but also an API exposed to JavaScript for querying or modifying the rendering through a system called “bindings”.</p><p>After the DOM tree, the next step is to process the CSS styles. For that, browsers have a CSS parser that builds a model of the style rules. Having built a model for style rules, we can merge them with a set of default styles supplied by the browser and compute the final value of every style property for every DOM element. This process is called style resolving (or recalc).</p><p>In the next layout part, we need to determine the visual geometry of all the elements. At this stage each element gets its coordinates (x and y), width, and height. The layout engine calculates and keeps records of all overflow areas — which part is visible and which is not.</p><p>As we have all the coordinates for all the elements, it’s time for painting<strong>. </strong>For this operation, we use coordinates from the previous step and color from the style rules and combine them into a list of painting instructions. It’s important to paint elements in the right order so they stack correctly when they overlap. You can modify order via the z-index style rule.</p><p>Let’s execute our list of painting instructions and convert them into a bitmap of color values. This stage is called “raster.”<strong> </strong>At this point we also take our images and decode them into bitmap.</p><p>Later, the rastered bitmap will be stored in GPU memory. This stage includes libraries that abstract the hardware and issuing calls to OpenGL and DirectX on Windows. When GPU receives the instructions to display bitmap, it draws pixels on your screen.</p><p>Now we have the most important parts of the rendering pipeline. But what happens if you scroll the page, or if animation is applied? In fact, rendering is not static. Change is represented via animation frames. Each frame is a complete rendering of the state of the content at a particular point in time. The real challenge in this process is its performance. Smooth animations require generation of at least 60 frames per second. It would almost impossible to complete a full pipeline 60 times in a second especially on slow devices.</p><p>What if instead of always re-rendering everything, we provide a way to invalidate an element at a specific stage. E.g. if you change the color of the button dynamically, the browser will mark this node as invalidated and it would be re-rerendered on the next animation frame. If nothing is changed we can reuse the old frame.</p><p>That’s a good way to optimize small dynamic changes in the content. Let’s think about change in big regions of content. For example, if we scroll the page, all pixels have to be different now. For that purpose a page is decomposed into layers that raster independently. A layer can be fairly small and represent only one DOM node. Those layers then will be combined together on another thread called <em>the compositor thread.</em><strong> </strong>With this optimization you don’t need to re-raster everything — just for small layers and then correctly combine them together.</p><p>Now we have had an overview of what Blink does and how rendering pipeline looks like, let’s dive into the code.</p><h3>Navigating the Blink Codebase</h3><p>We’re finally at the finish line. Let’s open the <a href="https://chromium.googlesource.com/chromium/blink/+/master/Source">Blink repository</a> and look around.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DuiyiPFzjJ5dl0qrPMaITw.png" /><figcaption>The root folder of Blink repository</figcaption></figure><p>We quickly realize that even though we’ve narrowed things down a lot from our original question, it’s still too big to manually find the specific line of code responsible for preventing focus.</p><p>Let’s try to search by our event name in Google:</p><pre>mousedown site:<a href="https://chromium.googlesource.com/chromium/blink/+/master/Source">https://chromium.googlesource.com/chromium/blink/+/master/Source</a></pre><p>This leads us to the <a href="https://chromium.googlesource.com/chromium/blink/+/master/Source/core/input/EventHandler.cpp#972">EventHandler</a> file where you can find implementation details for a lot of input events, including the most important line for us:</p><pre>bool swallowEvent = !dispatchMouseEvent(EventTypeNames::mousedown, mev.innerNode(), m_clickCount, mouseEvent);</pre><p>dispatchMouseEvent return value means “continue default handling”, so swallowEvent is true in case of preventDefault usage.</p><p>Just below there is a call for focus event which is triggered only if swallowEvent == false.</p><pre>swallowEvent = swallowEvent || handleMouseFocus(MouseEventWithHitTestResults(mouseEvent, hitTestResult), sourceCapabilities);</pre><p>Apart from focus handling, you can explore all default actions of the mouse down event, including selection, drag-drop, and scrollbar cases. It also implements mouse release and double clicks events. It’s all there.</p><h3>Gecko and WebKit</h3><p>At this point, we already spent some time discovering browser source code and have a pretty good understanding of their structure, so why not check Firefox and Safari altogether. Firefox’s browser engine is called Gecko and Safari’s is called WebKit.</p><p>Gecko also has an <a href="https://wiki.mozilla.org/Gecko:Overview">overview page</a> for developers, so you’ll get an idea of the main concepts behind it. Based on the experience with Chrome, you can find a neat 6000 lines of code in the <a href="https://github.com/mozilla/gecko-dev/blob/master/dom/events/EventStateManager.cpp#L3177">EventStateManager</a> file, with events default actions and behavior. I’ve included a specific line in the link, so you won’t have to go through it all.</p><p><a href="https://webkit.org/">WebKit</a> is a browser engine from Apple used in Safari and other Apple products. Chrome’s Blink was forked from WebKit, so they have a lot of things in common and it wasn’t a problem to find events implementation in their version of <a href="https://github.com/WebKit/webkit/blob/1321fa346ad792f6de3ace65ca98cbe3957a96c6/Source/WebCore/page/EventHandler.cpp#L1757">EventHandler</a> file.</p><p>Now, since we made sure we can prevent a mousedown event safely, I can step back and finish the PR with the date picker.</p><h3>Conclusion</h3><p>Together we went a journey from a simple problem to the introduction of Web Standards and browser implementation details.</p><p>Don’t be scared by the hidden complexity of existing modules, even if it’s a browser or compiler. It will be a fun journey in the end. The chances are you can easily find things to improve. More importantly, you will get unique insights into how things actually work. I’ve learned a ton of stuff in this deep dive and I encourage everyone to do the same. Browsers provide excellent documentation along the way — I’m not sure that I need anything else!</p><h3>Further Reading</h3><ul><li>Do you know what DOM is? How it’s represented internally? What’s the purpose of events? I highly recommend the <a href="https://dom.spec.whatwg.org/">DOM Standard</a> to everyone from beginners to more experienced developers. My favorite part: <a href="https://dom.spec.whatwg.org/#action-versus-occurance">“An event signifies an occurrence, not an action.”</a></li><li>Official website of the <a href="https://www.w3.org/">W3C</a> community.</li><li><a href="https://www.chromium.org/developers/how-tos/getting-around-the-chrome-source-code">Getting around Chromium codebase</a>.</li><li><a href="https://www.chromium.org/developers/design-documents">Design documents</a> published by Chromium developers.</li><li><a href="https://docs.google.com/presentation/d/1boPxbgNrTU0ddsc144rcXayGA_WF53k96imRH8Mp34Y/edit">Life of a pixel</a> — introduction into rendering pipeline of Chrome.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3876697920b1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/what-are-web-standards-and-how-do-they-work-with-web-browsers-3876697920b1">What Are Web Standards and How Do They Work With Web Browsers?</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Build an API Client Library in JavaScript]]></title>
            <link>https://medium.com/better-programming/how-to-build-an-api-client-library-in-javascript-665df869bdd5?source=rss-67fde4696dbe------2</link>
            <guid isPermaLink="false">https://medium.com/p/665df869bdd5</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[open-source]]></category>
            <dc:creator><![CDATA[Ilya Lyamkin]]></dc:creator>
            <pubDate>Wed, 29 Apr 2020 17:25:56 GMT</pubDate>
            <atom:updated>2020-04-29T17:25:56.165Z</atom:updated>
            <content:encoded><![CDATA[<h4>Creating your own JavaScript wrapper for an API</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9jx43qwZvelrAuAo" /><figcaption>Photo by <a href="https://unsplash.com/@jzamora?utm_source=medium&amp;utm_medium=referral">j zamora</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a>.</figcaption></figure><p>Every time I find myself connecting to a third-party API that doesn’t have a client library, I have to create a lot of boilerplate around it:</p><ul><li>Manually getting and passing authentication credentials to the data-fetching layer. What if you want to persist API keys or perform the OAuth process?</li><li>Defining data models and normalization. You would need to make sure that the data you receive from the API is saved in a structured way.</li><li>Create a controller for the API that keeps all the methods in one place so you can easily modify and find all usages of the API across your codebase.</li><li>Keeping up with updates. The APIs tend to change a lot. New methods come, old ones deprecate.</li></ul><p>It was one of these days where I decided to connect to <a href="https://docs.dev.to/api/">DEV API</a> to automatically collect stats for my published articles. There wasn’t any API client ready for use, so I ended up creating all of the wrapping logic around it. If it’s already there, then why not share it with others together with my learnings, right? We’ll go through five steps and come out with a clear plan on how to implement your own client.</p><h3>1. Language and Target Platform</h3><p>Before jumping into the coding part, let’s discuss which language we’re going to use. Remember my point about defining data models? For API clients, it’s essential to give a user more information about data that is going be returned so we don’t have to constantly switch context between documentation and IDE. It also helps to avoid bugs and typos as you write code. We all have tests in the end, don’t we? Keeping all that in mind, the best choice at the moment is to use TypeScript.</p><p>Now let’s think about where our library is going to be run. Basically, it could a browser or a Node.js server. Why not develop a library that works in both? It’ll also make it easier to use it together with server-side rendering where code is executed on the server first and then on the client.</p><h3>2. Bundling</h3><p>Two major differentiators for any library are its size and support of users with old and modern clients. First, we want our size to be as small as possible — an API client shouldn’t add much weight to the project. Second, the library should have decent browser support by serving the CommonJS bundle for those who cannot support the modern version and at the same time give a modern bundle for clients with newer versions.</p><p>The default choice for a web project is <a href="https://webpack.js.org/">Webpack</a>, but our library is fairly small and simple, so I’ve chosen <a href="https://rollupjs.org/">Rollup</a> as a base bundler together with <a href="https://github.com/developit/microbundle">microbundle</a> for easy setup.</p><pre>npm i -D microbundle</pre><p>Now update the package.js with build tasks and a path to an entry point:</p><pre>{<br>  &quot;source&quot;: &quot;src/foo.js&quot;,          // Your source file (same as 1st arg to microbundle)<br>  &quot;main&quot;: &quot;dist/foo.js&quot;,           // Output path for CommonJS/Node<br>  &quot;module&quot;: &quot;dist/foo.module.js&quot;,  // Output path for JS Modules<br>  &quot;unpkg&quot;: &quot;dist/foo.umd.js&quot;,      // Optional, for unpkg.com<br>  &quot;scripts&quot;: {<br>    &quot;build&quot;: &quot;microbundle&quot;,        // Uses &quot;source&quot; and &quot;main&quot; as input and output paths by default<br>    &quot;dev&quot;: &quot;microbundle watch&quot;<br>  }<br>}</pre><h3>3. Structure of the Library</h3><p>As we intend to support a lot of API endpoints, we want our code to scale well if the API expands. One of the best ways to do that is to align folders with resource names. For <a href="https://docs.dev.to/api/">Dev.to API</a>, it would look like this:</p><pre>/src<br>	/articles<br>		index.ts // Everything that&#39;s related to articles<br>		...<br>	/comments<br>		index.ts<br>		...<br>	/users<br>		...<br>	index.ts // Imports and joins all resources together</pre><p>It’s also useful to keep resources as separate classes so you don’t need to change root index.ts every time you add a new method. Then you&#39;d need to merge them together using <a href="https://www.typescriptlang.org/docs/handbook/mixins.html">TypeScript Mixins</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/291c61f01e1a8531c13262c03e5f86e3/href">https://medium.com/media/291c61f01e1a8531c13262c03e5f86e3/href</a></iframe><h3>4. Fetching the Library</h3><p>We wanted to make a library that works both in the browser and in Node.js. How we would make our requests universal as well? fetch is available in the browser but missing in Node.js, where you should use the http module.</p><p><a href="https://github.com/developit/unfetch/tree/master/packages/isomorphic-unfetch">isomorphic-unfetch</a> will help us use the fetch function everywhere and switch between the browser and Node.js versions automatically.</p><p>Now let’s have a look at the request function that wraps fetch and append an authentication header:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8fbc1ad39afd21ebf5933cbd3bb317b/href">https://medium.com/media/d8fbc1ad39afd21ebf5933cbd3bb317b/href</a></iframe><p>We always return Promise so clients can chain requests together or wait for the results.</p><h3>5. Testing</h3><p>Most of the code in the API client is integrated with third-party endpoints. To make testing easier, we can utilize the <a href="https://github.com/nock/nock">Nock</a> library that conveniently mocks an HTTP server for you:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3f48445e07af9dcc16420f779e6de26/href">https://medium.com/media/a3f48445e07af9dcc16420f779e6de26/href</a></iframe><p>In the example above, we set up the mock, then made the request, and finally checked that the mock has been executed.</p><h3>Conclusion</h3><p>We built an API client that is small, scalable, supports TypeScript out of the box, and works in a browser and in Node.js.</p><p>If you want to see the final code, feel free to check out the <a href="https://github.com/ilyamkin/dev-to-js">repository</a>. Don’t hesitate to ask me for the details or suggest an improvement.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=665df869bdd5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/how-to-build-an-api-client-library-in-javascript-665df869bdd5">How to Build an API Client Library in JavaScript</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Truly Reusable Design Systems in Practice]]></title>
            <link>https://medium.com/better-programming/truly-reusable-design-systems-in-practice-b6a07d7e59e9?source=rss-67fde4696dbe------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6a07d7e59e9</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[web-components]]></category>
            <dc:creator><![CDATA[Ilya Lyamkin]]></dc:creator>
            <pubDate>Thu, 02 Jan 2020 16:21:30 GMT</pubDate>
            <atom:updated>2020-01-02T16:21:30.820Z</atom:updated>
            <content:encoded><![CDATA[<h4>What makes a great design system — and how can you create your own for your project or company?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lBoVOpn2Ems8ZUw_" /><figcaption>Photo by <a href="https://unsplash.com/@alvaroreyes?utm_source=medium&amp;utm_medium=referral">Alvaro Reyes</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Companies like Airbnb, Apple, Uber, and GitHub have changed the ways they design digital products by incorporating their design language and organizing it into a system that can be used across all employees — and even outside of the company.</p><p>It quickly became popular in the whole industry: Just google the company’s name and the word “design” next to it, and you’d be surprised by how many companies have something similar. <a href="https://airbnb.design/the-way-we-build/">Airbnb Design</a>, <a href="https://developer.apple.com/design/">Apple Design</a>, <a href="https://baseweb.design/">Uber Base Web</a>, <a href="https://primer.style/">GitHub Primer </a>— these are the examples of good design systems.</p><p>We won&#39;t be talking today about the reasoning behind having a company-wide design system or the organizational challenges that come with it (though it’ll be definitely covered later, so stay tuned). Instead, we’ll focus on the technical choices and implementation details.</p><h3>Traits of a Good Design System</h3><p>A good design system is a collection of reusable components — guided by clear standards — that can be assembled together to build any number of applications. Let’s try to split this definition into actionable traits we want to prioritize and focus on from a technical perspective.</p><h4>Reusable components</h4><p>Generally speaking, the design system is a set of shared components that’ll be used by everyone.</p><p>Imagine you have several independent teams in the company, and some of them use vanilla JS. Another team uses React, and even another group is experimenting with Svelte. As a creator of a design system, you have to build components for these frameworks and think about flexibility in the feature, so you won’t lock other developers in a specific ecosystem.</p><h4>Extensive documentation</h4><p>To ensure the smooth adoption of your design system, you’ll have to provide thought-through, easy-to-use documentation with examples and best practices.</p><p>How do you do this? First, a website with all components and their descriptions would help. Second, it’d be amazing if you could provide guidance about possible arguments and use cases for your components directly in the developer’s IDE.</p><h4>Performance-oriented</h4><p>So you’re about to ask your fellow developers to add this design system as a dependency and probably replace something that’s already working, make sure to keep the number of dependencies as low as possible, preferably zero, so you won&#39;t bloat the package size of all projects.</p><p>Try to rely on a browser API or CSS and be closer to browser-native behavior because less custom JS code means faster components.</p><h4>Maintain the highest quality</h4><p>You also need to ensure your design system won’t break on a new release. Apart from doing code review and manual testing, I’d encourage everyone to look at automated tests. For presentational components, consider <a href="https://storybook.js.org/docs/testing/automated-visual-testing/">screenshot testing</a>. For stateful ones, write integration and end-to-end tests.</p><h3>StencilJS and Web Components to the Rescue</h3><p>If you’re wondering how you’re going to cover everything from the list above without spending a month setting up the architecture, I have something to suggest.</p><p><a href="https://stenciljs.com/">StencilJS</a> is a toolchain for creating reusable, scalable design systems built on top of Web Components. It provides a complete set of tools to start working on your design system right now and makes it easy to work with Web Components.</p><p>The components created with Stencil are fully compatible with browser standards and can be run in any framework, including just a plain HTML file. You can use <a href="https://stenciljs.com/docs/output-targets">output targets</a> to add a custom website that’ll showcase your work. It also features <a href="https://stenciljs.com/docs/screenshot-visual-diff">screenshot testing</a> (apart from e2e and Jest integration).</p><p>Let’s dive into it, and see how easy it is to build a simple-yet-stateful component.</p><h4>Introducing the fetch button</h4><p>The core component of any design system is a button. But since just a button would be too simple, we’ll make it powerful enough to also fetch data from any endpoint you specify in its attributes and return data via browser events.</p><p>To start, run the Stencil generator: npm init stencil. It’ll ask you to pick a starter. Choose Component. That’ll generate a folder with a simple test component so you can start playing with it (npm install &amp;&amp; npm start).</p><p>In the src/components folder, you’ll find themy-component folder. Rename it to fetch-button — as well as the css and tsx files inside of it. The CSS file is responsible for the styling of our button, so let’s add some styles:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/754f64b54e3405dab8c2851fac8d8563/href">https://medium.com/media/754f64b54e3405dab8c2851fac8d8563/href</a></iframe><p>Now go to thetsx file. This is the actual component we need to build.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb1d94cd7630bdac70e5737565e0986b/href">https://medium.com/media/bb1d94cd7630bdac70e5737565e0986b/href</a></iframe><p>Before the component class, we need to add a decorator specifying the tag name, a path to the style file.</p><p>Then inside of the class, we need to define a prop called url. It’ll work as an HTML attribute and allow us to pass data to the component.</p><p>The next line creates a state variable: Every time we change it, the render function will rerun.</p><p>The @Eventdirective registers two events for us: onSuccess and onError .</p><p>@Listen helps us to listen to click events and execute the corresponding function. In our case, we’ll call the native fetch function and update the state and trigger events depending on the outcome.</p><p>Finally, therender function defines the DOM that‘ll’ be created. The &lt;slot /&gt; tag will be replaced by &lt;fetch-button&gt; children.</p><p>That’s it. Now let’s see how we can use it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/62662f68bf8f66916ec62efde5bc4da4/href">https://medium.com/media/62662f68bf8f66916ec62efde5bc4da4/href</a></iframe><p>Apart from the native HTML example, I’ve added integration with React. As you can see, it’s as easy as writing plain div elements.</p><h3>Known Complexities</h3><p>Now, it’s time to talk about the downsides of using Web Components.</p><p>The most important one is the lack of good framework support. For example, in React, you can’t attach event listeners to your component.</p><p>As a workaround, you can attach a native event using theref property — which is what I did in the example above. The <a href="https://custom-elements-everywhere.com/">Custom Elements Everywhere</a> website shows the compatibility Web Components has with popular frameworks.</p><h3>Conclusion</h3><p>Before starting working on the design system, evaluate the values you want to focus on. Maybe you don’t need to have it at all and just properly organized shared components would be enough for you.</p><p>If you’ve decided to incorporate the system, Web Components perfectly solves challenges that stand before design systems and is a great technology to build your components upon.</p><p>StencilJS makes it easy to manage and deliver components for different targets. But with all that in mind, beware and explore the still-standing issues regarding framework support.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6a07d7e59e9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/truly-reusable-design-systems-in-practice-b6a07d7e59e9">Truly Reusable Design Systems in Practice</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Hackathons Make You a Better Developer]]></title>
            <link>https://medium.com/better-programming/why-hackathons-make-you-a-better-developer-81ef8f4a9385?source=rss-67fde4696dbe------2</link>
            <guid isPermaLink="false">https://medium.com/p/81ef8f4a9385</guid>
            <category><![CDATA[personal-growth]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[creativity]]></category>
            <category><![CDATA[hackathons]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Ilya Lyamkin]]></dc:creator>
            <pubDate>Mon, 25 Nov 2019 23:41:52 GMT</pubDate>
            <atom:updated>2019-11-25T23:41:52.808Z</atom:updated>
            <content:encoded><![CDATA[<h4>Pressure makes better programmers, faster</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PlHiRUG5GFvqH1yH" /><figcaption>Photo by <a href="https://unsplash.com/@impatrickt?utm_source=medium&amp;utm_medium=referral">Patrick Tomasso</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Over the course of my life, I’ve participated in more than 20 hackathons, so I might be a little biased on them, but on the other hand, I know a lot about how they can be useful.</p><p>Let me start by explaining what a hackathon means to me. In general, it’s an event of short duration (usually one or two days) where people come together to creatively solve problems. Hackathons can be themed, where the projects are confined to a particular problem such as food sustainability or returning citizens.</p><h3>Reasons to Participate in Hackathons</h3><p>Now that we have covered the definition, we can start with the reasons why you’ll become a better developer by participating in hackathons.</p><h4>Extreme programming</h4><p>It’s very easy to forget about speed while working with Scrum processes, so let’s bring the former back. With short deadlines and ambitious ideas, hackathons teach you how to code fast and, more importantly, think fast.<br>If you’re wondering why it’s that important, the reason is that you’ll know your limits much better and will be able to push them even further after the hackathon. You’ll not only be surprised by how much you have achieved but also understand your areas of growth.</p><h4>Learning how to estimate your efforts better</h4><p>Due to the limited time, proper estimation is essential for your success. If your estimation is incorrect, you won’t be able to achieve what you planned in time. The truth is, at a hackathon, you’ll notice that your estimations are far from perfect. Use this fact to your advantage and adjust your estimations so that it doesn’t happen at work.</p><h4>Creative thinking</h4><p>Hackathons teach you how to solve a known problem creatively. In the first stage, ideation, you have to come up with a unique and fresh idea. If you think that’s all, actually, this is just the beginning. Now it’s time for execution, and you have to be creative at every step of the way because you’ll never have enough time or well-defined processes. Something will always break most unexpectedly, and you’ll need to find a viable solution to be able to ship the product in time.</p><h4>Learning new technology</h4><p>Hackathons are perfect places to learn something new. If you use React.js at work, try Svelte. Writing back-end with Java? Learn Kotlin! Or completely switch your stack from front end to back end, and the other way around. Maybe you want to get into VR. This is your chance.</p><h4>Networking</h4><p>Hackathon is an excellent chance to talk to fellow developers and like-minded people. You can get a big picture of what they’re working on and which tools they’re currently using. Think of it as a conference where you also have to code.</p><h4>Iteration-based approach</h4><p>At hackathons, you should focus on building a minimum viable product, which means you should be able to drop parts that are not required and then iterate over it. That’d allow you to ship a product where you can show something to people even if you can’t finish this cool new feature in time.</p><h4>Learning how to split tasks in the best way</h4><p>If your team consists of four or five people, you have to make sure your team works as one organism and utilizes the abilities of each team member. Be ready to communicate with your team actively and split the product into several independent pieces. Without proper separation of concerns, four people would work as two with clearly divided tasks.</p><h4>Shifting focus to bring business value</h4><p>In our work, you can easily forget why you’re writing code and what value it brings to the end user. On the other hand, at hackathons, you’re solving real-world challenges — and thinking about them in the first place. It shifts your vision from just code to a big picture of what you’re trying to archive.</p><h4>Workshops</h4><p>It’s popular to have workshops that you can attend at the time of the event. They could be about new technology or about soft skills like improving your resume. They can be highly beneficial if you have just started your career or want to learn something new.</p><h4>Getting feedback</h4><p>Hackathons are one of the best places for validating your ideas. In your normal life, it’s hard to find someone who will be both honest and willing to spend time reviewing your ideas. Other options include using your personal network or paying for ads. At hackathons, you get all of that for free, and from people like you.</p><h4>Giving feedback</h4><p>I know a lot of people who find joy in helping and teaching others. By doing so, you can learn what others are doing and, if you have expertise in that area, help them. The best way to grow your network is to be helpful, so actively seek out these opportunities.</p><h4>Having fun</h4><p>Ultimately, this is what hackathons are all about. Don’t worry if you’re not going to be able to present a perfect product, just have fun. If your hackathon takes place in a different city or country, take advantage. Get to know the local culture and engage in unique experiences.</p><h3>How To Get Started</h3><p>If you decide to give hackathons a chance, there are several resources to check out.</p><p>The first is Major League Hacking (MLH). It’s the official student hackathon league that runs over <a href="http://mlh.io/events">200 weekend-long invention competitions</a>.<br>Second, make sure to go over <a href="https://hackjunction.com/">Junction Hackathon</a> and <a href="https://techcrunch.com/events/disrupt-sf-2019/hackathon/">TechCrunch Disrupt Hackathon</a>. They’re one of the biggest independent hackathons in the world.<br>Last but not least, check <a href="https://www.meetup.com/">Meetup</a> to find local hackathons in your city.</p><h3>Conclusion</h3><p>I hope I convinced you to take a look at hackathons. It would definitely not be easy to code for two days non-stop, but the results will pay off. You’ll learn a lot about yourself and your limits, find out how to estimate and split tasks, and understand how to apply your skills to solve real-world challenges. And don’t forget to have fun.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81ef8f4a9385" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/why-hackathons-make-you-a-better-developer-81ef8f4a9385">Why Hackathons Make You a Better Developer</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing the Prefetch Pattern in React Concurrent Mode]]></title>
            <link>https://medium.com/better-programming/implementing-the-prefetch-pattern-in-react-concurrent-mode-c10c9813e2e7?source=rss-67fde4696dbe------2</link>
            <guid isPermaLink="false">https://medium.com/p/c10c9813e2e7</guid>
            <category><![CDATA[data-fetching]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Ilya Lyamkin]]></dc:creator>
            <pubDate>Mon, 04 Nov 2019 00:17:58 GMT</pubDate>
            <atom:updated>2019-11-04T00:17:58.461Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Fetch-on-render, fetch-then-render, render-as-you-fetch</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ILWRp2xtp-DeNfKc" /><figcaption>Photo by <a href="https://unsplash.com/@franki?utm_source=medium&amp;utm_medium=referral">Franki Chamaki</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Recently, React announced a feature of the React ecosystem — <a href="https://reactjs.org/docs/concurrent-mode-intro.html">Concurrent Mode</a>. This would allow us to stop or delay the execution of components for the time that we need. It’ll help React apps stay responsive and gracefully adjust to the user’s device capabilities and network speed.</p><p>Concurrent Mode consists of a set of new features — one of the biggest ones is <em>suspense</em> and a new approach to data fetching.</p><p>Basically, there are three ways to do it:</p><ul><li>Fetch-on-render: We start rendering components and each of these components may trigger data fetching in their effects and lifecycle methods. A good example of that is fetch in useEffect.</li><li>Fetch-then-render: Start fetching all the data for the next screen as early as possible. When the data is ready, render the new screen. We can’t do anything until the data arrives. The example of that is having a Container component that handles data fetching and conditionally renders the child presentational component once we’ve received everything.</li><li>Render-as-you-fetch: Start fetching all the required data for the next screen as early as possible, and start rendering the new screen <em>immediately, even before we get a network response</em>. As data streams in, React retries rendering components that still need data until they’re all ready.</li></ul><p>I believe that the concepts of the first two approaches are well known and definitely presented in your code. Let’s dive straight into the render-as-you-fetch<strong> </strong>approach.</p><h3><strong>Render-As-You-Fetch</strong></h3><p>You’ve probably noticed that the explanation of this approach has two parts:</p><ul><li>Start loading data as early as possible.</li><li>Start trying to render components that may still need data.</li></ul><h4>Fetch early</h4><p>Let’s build an app together that loads major stock indexes. For that, we have a simple “Load” button. Once you click on it, we start loading data immediately:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/440e353b670cb86880f4a3e7ff5565e0/href">https://medium.com/media/440e353b670cb86880f4a3e7ff5565e0/href</a></iframe><p>prefetchQuery is a function that performs the fetch request and returns an object that we’re going to pass to the &lt;IndexList /&gt; component. The key takeaway from this example is that we’re triggering fetch from the onClick event and not in the render phase.</p><h4>Render early with Suspense</h4><p>The second part of the example above is that we’re saving the object from prefetchQuery to the state and starting to render &lt;IndexList /&gt; immediately as well.</p><p>On the other hand, we also don’t want to render the list with empty data, so ideally, we’d like to be able to suspend render until we have all the data without writing if (isLoading) return null. Luckily, we have <a href="https://reactjs.org/docs/concurrent-mode-suspense.html">the</a><a href="https://reactjs.org/docs/concurrent-mode-suspense.html">Suspense component</a> for exactly that purpose.</p><p>Suspense is a mechanism for data-fetching libraries to communicate to React that <em>the data a component is reading is not ready yet</em>. React can then wait for it to be ready and update the UI.</p><p>Let me show you an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf434d10f13bb644ebb5a3e7b5bb66bb/href">https://medium.com/media/cf434d10f13bb644ebb5a3e7b5bb66bb/href</a></iframe><p>To take advantage of Suspense, you just need to wrap your component with it. It accepts a fallback prop: the element that you want to show while waiting for data.</p><h3>How To Fetch Data in Sync With Suspense?</h3><p>Now that you know about Suspense and prefetch practices, you wonder how this all works together. So, here is the last piece of this puzzle. To solve it, let’s finally check out the prefetchQuery function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe9dd3fc809565da95bb370f8a246e6b/href">https://medium.com/media/fe9dd3fc809565da95bb370f8a246e6b/href</a></iframe><p>Don’t be scared by the complexity of it, it’s actually fairly simple.</p><p>First, we take a URL and pass it to the native fetch function, receive a promise, and pass it to the wrapPromise function. This function returns an object with the read() method:</p><ul><li>If a promise is still pending, we throw this promise.</li><li>If a promise is resolved with error, we throw the error.</li><li>If a promise is resolved, just return the data.</li></ul><p>In fact, the only difference we have, compared to traditional fetching practices, is throwing a pending promise.</p><p>When you have usePrefetchedQuery in IndexList, it just executes the read() method. If data is not there yet, it throws a promise before actually rendering anything and Suspense will catch that.</p><h3>How To Experiment With This?</h3><p>The React team introduced <a href="https://reactjs.org/docs/concurrent-mode-adoption.html">an </a><a href="https://reactjs.org/docs/concurrent-mode-adoption.html">experimental releases</a> branch with a modern API.</p><p>For that, you need to run npm i react@experimental react-dom@experimental and play with it locally. I also created a live example on <a href="https://codesandbox.io/s/prefetch-suspense-6q4gj">CodeSandbox</a> for you that shows everything I did together in one working project.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fprefetch-suspense-6q4gj%3Ffontsize%3D14&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fprefetch-suspense-6q4gj%3Ffontsize%3D14&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F6q4gj%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/d171bb5b42975654fcfeb14df85e8b47/href">https://medium.com/media/d171bb5b42975654fcfeb14df85e8b47/href</a></iframe><h3>Can I Use It in My Production Projects?</h3><p>No.<strong> </strong>Concurrent mode is still under development and some implementation details could change. Use experimental versions to get familiar with new concepts and maybe propose your own ideas. For example, how to integrate prefetch practices in routers or provide a good way to cache data.</p><h3>Further Resources</h3><ul><li><a href="https://relay.dev/docs/en/experimental/a-guided-tour-of-relay">An experimental version of Relay with Suspense</a>.</li><li>Soon, you’ll be able to connect preload functionality to routers. Have a look at <a href="https://github.com/ReactTraining/react-router/pull/7010">https://github.com/ReactTraining/react-router/pull/7010</a> or <a href="https://github.com/frontarm/navi">Navi router</a>.</li><li><a href="https://reactjs.org/docs/concurrent-mode-intro.html">Introduction to Concurrent mode</a>.</li><li><a href="https://reactjs.org/docs/concurrent-mode-suspense.html">Introduction to Suspense for data fetching</a>.</li><li><a href="https://codesandbox.io/s/prefetch-suspense-6q4gj">Live sandbox with examples</a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c10c9813e2e7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/implementing-the-prefetch-pattern-in-react-concurrent-mode-c10c9813e2e7">Implementing the Prefetch Pattern in React Concurrent Mode</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adventuring Into React Hooks Performance Practices]]></title>
            <link>https://medium.com/better-programming/adventuring-into-react-hooks-performance-practices-77a23825a946?source=rss-67fde4696dbe------2</link>
            <guid isPermaLink="false">https://medium.com/p/77a23825a946</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react-hook]]></category>
            <dc:creator><![CDATA[Ilya Lyamkin]]></dc:creator>
            <pubDate>Thu, 17 Oct 2019 22:46:37 GMT</pubDate>
            <atom:updated>2019-10-17T22:46:37.157Z</atom:updated>
            <content:encoded><![CDATA[<h4>Performance pitfalls and how to avoid them</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mH64FyEHDw9z-2xC" /><figcaption>Photo by <a href="https://unsplash.com/@rockthechaos?utm_source=medium&amp;utm_medium=referral">Kolleen Gladden</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>From version 16.8.0, React introduced us to a way to use state and other React features without writing a class — <a href="https://reactjs.org/docs/hooks-intro.html">React Hooks</a>.</p><p>It’s an amazing improvement around <a href="https://reactjs.org/docs/react-component.html">the classic Class paradigm</a> which allows us to reuse stateful logic between components. No surprise that it comes with a learning curve that could lead to performance pitfalls.</p><p>Let’s deep dive into the most popular ones and try to figure out how to avoid them.</p><h3>Re-Renders Matter</h3><p>Alright, we identified that we may encounter some performance issues while using Hooks, but where are they coming from?</p><p>Essentially, most of the issues with Hooks come from unnecessary renders of your components. Have a look at the following example:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fincrementor-46w3y%3Fexpanddevtools%3D1%26fontsize%3D14&amp;src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fincrementor-46w3y%3Fexpanddevtools%3D1%26fontsize%3D14&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/102c75140c3ac8563e6d7a148b7988e0/href">https://medium.com/media/102c75140c3ac8563e6d7a148b7988e0/href</a></iframe><p>This is a component that has two states, A and B, and four increment actions on them. I’ve added the console.log method to see the message on every render. The first two actions are basic increments and just increase A or B values by one.</p><p>Let’s click on the <em>a++, b++</em> button and have a look at the console: on each click, there should be only one render. This is really good because that’s what we wanted.</p><p>Now press the <em>a++, b++ after 1s</em> button: on each click, you’d see two renders. If you’re wondering what’s happening underneath — the answer is simple.</p><p>React batches synchronous state updates into one.</p><p>On the other hand, for asynchronous functions, each setState function triggers a render method.</p><p>But what if you want to have consistent behavior? Here comes the first rule of Hooks.</p><h3>Rule 1: Do Not Split State Between Several useState Methods for Connected Data Models</h3><p>Imagine you have two independent states. Then, the requirements changed, thus update of one state causes an update of another one.</p><p>In this case, you have to join them in one object: const { A, B } = useState({ A: 0, B: 0}). Or, take advantage of the <a href="https://reactjs.org/docs/hooks-reference.html#usereducer">useReducer</a> function.</p><p>Another good example of this rule is data loading. Usually, you need three variables to handle it: isLoading, data, and error. Don’t try to keep them separate, prefer useReducer instead.</p><p>It allows you to separate state logic from components and helps you to avoid bugs. Having one object with these three properties will be a solution as well but would not be that explicit and error-prone.</p><p>Trust me on that, I have seen so many people forgetting to set isLoading: false on error.</p><h3>Custom Hooks</h3><p>Now that we’ve figured out how to manage useState in a single component, let’s move increment functionality outside to be used in different places.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29c4ebfaa2d312aa4d1348269cb50ddd/href">https://medium.com/media/29c4ebfaa2d312aa4d1348269cb50ddd/href</a></iframe><p>We refactored the increment logic to its own Hook and then we run it once using the <a href="https://reactjs.org/docs/hooks-reference.html#useeffect">useEffect</a> function.</p><p>Note that we have to provide the incrementA setter in the dependency array because we’re using it inside and it’s enforced by <a href="https://www.npmjs.com/package/eslint-plugin-react-hooks">Hook’s ESLint rules</a>. (Please enable them if you didn’t do that before!).</p><p>If you try to render this component, your page will be frozen because of infinite re-renders. To fix it, we need to define the second rule of Hooks.</p><h3>Rule 2. Make Sure You Return New Objects From Custom Hooks Only If They’ve Changed</h3><p>The component above is always re-rendering because the increment Hook returns a new function every time. To avoid creating a new function every time, wrap it in the <a href="https://reactjs.org/docs/hooks-reference.html#usecallback">useCallback</a> function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe5cd0d716a1eb1b3afcb51fe8911ed5/href">https://medium.com/media/fe5cd0d716a1eb1b3afcb51fe8911ed5/href</a></iframe><p>Now it’s safe to use this Hook.</p><p>Sometimes, you need to return a plain object from custom Hooks, make sure you update it only when its content changes using <a href="https://reactjs.org/docs/hooks-reference.html#usememo">useMemo</a>.</p><h3>How to Find These Re-Renders Before It’s Too Late?</h3><p>Normally, it’s troublesome to find these issues before it causes performance issues, so you have to use specific tools to detect them beforehand.</p><p>One of them is the <a href="https://github.com/welldone-software/why-did-you-render">why-did-you-render</a> library that tells you about avoidable re-renders. Mark your component as MyComponent.whyDidYouRender = true, start interacting with it, and look for messages in the console.</p><p>I guarantee that you’ll discover something new in the next five minutes.</p><p>Another option is to use the <em>Profiler</em> tab in <a href="https://github.com/facebook/react/tree/master/packages/react-devtools">React Dev Tools extension</a>. Although you have to think about how many re-renders you expect from your component— this tab only shows the number of re-renders.</p><p>Let me know what other challenges you’ve encountered with Hooks, let’s solve them together.</p><h3>References and Further Resources</h3><ul><li><a href="https://reactjs.org/docs/hooks-reference.html">React Hooks API</a>.</li><li><a href="https://kentcdodds.com/blog/profile-a-react-app-for-performance">How to profile React apps with Dev Tools Profiler</a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77a23825a946" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/adventuring-into-react-hooks-performance-practices-77a23825a946">Adventuring Into React Hooks Performance Practices</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[You Might Not Need Controlled Components]]></title>
            <link>https://medium.com/@ilyamkin/you-might-not-need-controlled-components-903bc8847d7f?source=rss-67fde4696dbe------2</link>
            <guid isPermaLink="false">https://medium.com/p/903bc8847d7f</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[forms]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Ilya Lyamkin]]></dc:creator>
            <pubDate>Wed, 16 Oct 2019 18:41:06 GMT</pubDate>
            <atom:updated>2019-10-16T18:41:06.158Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*cEVEF4VNx3noAloAHX9SJw.jpeg" /></figure><p>If you&#39;ll go to the official React website it says that <a href="https://reactjs.org/docs/uncontrolled-components.html">the recommended way to use inputs is to control them via React state</a>. It also mentions that in some cases you can go with an uncontrolled option but do not say what are these cases explicitly. Let’s try to dive into it and see the pros and cons of this approach.</p><h3>It’s all about control</h3><p>Controlled input values are being kept in the local state. Every time the user changes the content of the input, the onChange function updates the React state, Component rerenders with the new value passed to Input.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6f3e465363cb2872fdfd45780e05de1/href">https://medium.com/media/b6f3e465363cb2872fdfd45780e05de1/href</a></iframe><h3>Let browser do its job</h3><p>On the other hand, uncontrolled inputs are being handled by the browser itself. So you don’t have direct control over inputs value in the component, but you can use ref to get access to it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c39c088d0d6f1257de4ce2c288ad5b5/href">https://medium.com/media/7c39c088d0d6f1257de4ce2c288ad5b5/href</a></iframe><p>Looking at these two examples you can clearly say that the second one looks cleaner and less verbose than the first one. You don’t need to instantiate state, pass the value to each input and override onChange handlers.</p><p>An uncontrolled form doesn’t have state, so every time you type, your component doesn’t rerender, increasing overall performance.</p><p>By leveraging uncontrolled inputs you’re trusting browser with form management and become closer to the native implementation. Why do you need to write something that was already created anyway? 🤔</p><h4>But what if I need to handle complex form, perform validation or handle custom submit logic?</h4><p>Use refs. With new Hooks API, refs became a more stable and better way to control DOM. Consider the following example where you need to access forms values outside of theonSubmit function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/671037927569b39444ee84c18e59fc20/href">https://medium.com/media/671037927569b39444ee84c18e59fc20/href</a></iframe><h4>Embrace HTML5</h4><p>Browser API provides you with a lot of useful features to handle forms and inputs.</p><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/reset">form.reset()</a> — use the reset function to clear all your fields</li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit">form.submit()</a> — use it to programmatically submit the form</li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/reportValidity">form.reportValidity()</a> — checks validation constraints and returns true or false</li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Document/forms">document.forms</a> — interface that allows you to access all forms on the page.</li><li><a href="https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation">Constraint Validation API </a>— set of properties and methods that allows you to create complex validations on the fields. min, max, pattern, email, required — all of that and much more is covered by it.</li></ul><h4>What about libraries that I can use with uncontrolled inputs?</h4><p>Sure! <a href="https://github.com/react-hook-form/react-hook-form">React-Hook-Form</a> allows you to build a form and perform validation on it without the hassle. <a href="https://github.com/Rocketseat/unform">Unform</a> helps you build complex forms with nested fields, validation using uncontrolled components.</p><h4>When it makes sense to use controlled inputs then?</h4><p>Basically you need to choose controlled inputs when <strong>you need to rerender</strong> your component on every type. For example, you want to display or send all form values as you type (imagine autocomplete field for the search bar). Or if you need to pass input value to child component through props. There are quite a few cases where you have to use it.</p><h3>Conclusion</h3><p>I believe that uncontrolled components are currently undervalued and should have more presence in modern React applications. Indeed they’re not gonna solve all your problems but would help increase the performance and reliability of your components in many cases.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=903bc8847d7f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Selecting Ideal Candidates: Looking Beyond the Resume]]></title>
            <link>https://medium.com/cvpicker/selecting-ideal-candidates-looking-beyond-the-resume-1191a4d9c490?source=rss-67fde4696dbe------2</link>
            <guid isPermaLink="false">https://medium.com/p/1191a4d9c490</guid>
            <category><![CDATA[video-interview]]></category>
            <category><![CDATA[job-hunting]]></category>
            <category><![CDATA[hiring]]></category>
            <dc:creator><![CDATA[Ilya Lyamkin]]></dc:creator>
            <pubDate>Wed, 14 Sep 2016 02:49:50 GMT</pubDate>
            <atom:updated>2016-09-14T02:54:42.159Z</atom:updated>
            <content:encoded><![CDATA[<p>When bringing on new employees, hiring managers always look for similar qualities. They seek employees who will show up on time, know what they are doing and will contribute, in one way or another, to the overall success of the company.</p><p>Unfortunately, everyone else is also aware of these ideal employment qualities. Resumes and cover letters will highlight attributes that fit in with these qualifications, regardless of the candidates’ actual punctuality, know-how and overall motivation to succeed. While resumes and cover letters are important aspects of the hiring process, there are other factors that should be considered.</p><h3>Confidence</h3><p>During an initial interview, candidates are likely to be nervous. If a person comes off as overly confident, this trait may indicate that he or she will not do well with constructive criticism down the road. Likewise, an individual who fidgets and stumbles over words may not do well under pressure. An ideal candidate should appear confident in his or her abilities yet remain grounded.</p><h3>Personality</h3><p>A candidate may not show their true personality during an interview, but chances are likely that a small glimmer of the “true self” will be revealed. A person who appears to be shy may not have much to say, which is not ideal for certain fields or positions and vice versa. In either case, some personalities are simply a better fit for particular positions and groups of existing co-workers.</p><h3>Body Language</h3><p>Approximately 93 percent of communication is non-verbal, with a whopping 55 percent of this non-verbal communication being body language. A candidate who slouches, yawns or does not make eye-contact may give away his or her lack of enthusiasm about the potential new job. Candidates who are truly interested will display their interest through eye-contact, sitting up straight and giving their full attention to what is being said.</p><h3>Creativity</h3><p>While most hiring managers have heard just about every answer possible to the typical interview questions, they should pay close attention to those with unique answers or questions. A candidate who gives typical responses may lack creativity. Those who answer questions with a new (but appropriate) approach may be helpful, if hired, in coming up with new methods or solutions to problems.</p><p>A hiring manger can easily determine if a candidate is a good fit for their needs by taking these matters into account along with the individual’s resume. While face-to-face meetings are traditional, preliminary video interviews through Skype or other applications are becoming increasingly popular. During video interviews, hiring managers are able to examine a candidate’s disposition before bringing them in for a face-to-face meeting which can drastically narrow down their list of potential new hires.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1191a4d9c490" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cvpicker/selecting-ideal-candidates-looking-beyond-the-resume-1191a4d9c490">Selecting Ideal Candidates: Looking Beyond the Resume</a> was originally published in <a href="https://medium.com/cvpicker">CVPicker</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>