<?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 Asís García on Medium]]></title>
        <description><![CDATA[Stories by Asís García on Medium]]></description>
        <link>https://medium.com/@asis.garcia?source=rss-83191ece38e6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*P40OcXy3OsXTQEB5rbBR6g.jpeg</url>
            <title>Stories by Asís García on Medium</title>
            <link>https://medium.com/@asis.garcia?source=rss-83191ece38e6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 17:29:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@asis.garcia/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[Why is React Declarative? A Story About Function Components]]></title>
            <link>https://medium.com/trabe/why-is-react-declarative-a-story-about-function-components-aaae83198f79?source=rss-83191ece38e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/aaae83198f79</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[rendering]]></category>
            <category><![CDATA[declarative-programming]]></category>
            <category><![CDATA[components]]></category>
            <dc:creator><![CDATA[Asís García]]></dc:creator>
            <pubDate>Mon, 09 Nov 2020 09:02:52 GMT</pubDate>
            <atom:updated>2022-07-04T10:58:50.146Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7rwPe6QJxIU67tbWhPPJNw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@loupbrun?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Lou Brassard</a> on <a href="https://unsplash.com/wallpapers/colors/grey?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p><a href="https://reactjs.org/">React</a> is <strong>declarative</strong>. It’s almost the first thing you are told about the library in its home page:</p><figure><img alt="A capture of React docs front page, with an arrow pointing to the heading “declarative”." src="https://cdn-images-1.medium.com/max/1024/1*hEOUK_U2WFZ0kgp9o8xGEw.png" /></figure><p>But, what does it mean? “Declarative”, at least in the programming sense, is usually defined as “telling what to do instead of how to do it”. When we talk about React being declarative, the most common explanation revolves around how when you write a component, you just tell React what do you want the DOM to look like, and just let React handle it from there. You don’t have to worry about how the different elements currently in the web page have to change, or which ones have to be removed or inserted. You just say “I want a button there, and I want it disabled”, and React makes it happen. “Now I want the button to be enabled”. No problem, React’s got your back.</p><p>So that’s one way of looking at it: React applications are declarative regarding the DOM manipulation. I like to think about this as the first declarative layer of React. Because there is a second layer: React components are also declarative regarding their own rendering.</p><h3>Components Rendering is Declarative</h3><p>Have you ever wondered what makes React function components different from plain JavaScript functions? Is there any difference?</p><p>No, there isn’t. “React function component” is just a fancy name for a JavaScript function. That’s clear when you define a React function component: you just define a JavaScript function. The real difference lies in the way you use that function.</p><p>Forget React for a second. What do you use functions for when programming plain JavaScript (or any other language for that matter)? A function is just a bunch of statements grouped as a unit, which you define with a single purpose: invoking it.</p><p>Now back to React: when do you invoke your component functions? Exactly! Never. React is the one invoking them. You use React elements to tell React which functions to invoke when rendering each component, but the library decides when to invoke them. That makes the rendering of components declarative.</p><h4>Imperative vs Declarative Rendering: an Example</h4><p>To better grasp the implications of declarative rendering, take a look at this example:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fdi9bc&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fdi9bc&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fdi9bc%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/7442ee27acfbbc182d08fc8d77164313/href">https://medium.com/media/7442ee27acfbbc182d08fc8d77164313/href</a></iframe><p>As you can see, we are using the Button component as a plain JS function (line 17): we call it passing the props we want it to use, and everything works fine.</p><p>Now, say we decide to handle the theme using <a href="https://reactjs.org/docs/context.html">React Context API</a> at the Box component level. Suddenly, the Button component stops working (it’s using the wrong theme):</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fsuvk2&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fsuvk2&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fsuvk2%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/27aeef26497f96784e8f17b5887a5046/href">https://medium.com/media/27aeef26497f96784e8f17b5887a5046/href</a></iframe><p>What’s going on here? React Context API is defined in terms of containment: nested components have access to the context exposed via Context Providers. OK, but isn’t our Button component nested inside the ThemeProvider component? The answer is: no, it isn’t. We’re not using Button as a component but as a plain function. Instead of letting React handle the rendering of Button, we render it by ourselves, invoking Button while React is still rendering Box. When we call the Hook to access the context value, React knows nothing yet about the ThemeProvider, because we are still rendering the Box component!</p><p>If we use Button as a component, everything works as expected:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fjxt5b&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fjxt5b&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fjxt5b%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/cb1f1e48ea4035a65050cb3618ec07b8/href">https://medium.com/media/cb1f1e48ea4035a65050cb3618ec07b8/href</a></iframe><p>Now we are using the function as a React function component: instead of invoking it, we tell React that we want it to invoke the function whenever it sees fit. We don’t render, we declare what we want React to render for us.</p><p>As we’ve seen, thinking about the differences between invoking a function component and returning a React element, and the implications it has regarding some React APIs, is a good exercise to better understand how rendering works in React, and the importance of rendering being “declarative”.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aaae83198f79" width="1" height="1" alt=""><hr><p><a href="https://medium.com/trabe/why-is-react-declarative-a-story-about-function-components-aaae83198f79">Why is React Declarative? A Story About Function Components</a> was originally published in <a href="https://medium.com/trabe">Trabe</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use Enzyme & Jest Snapshots to Test data-testid Attributes in React Components]]></title>
            <link>https://medium.com/trabe/use-enzyme-jest-snapshots-to-test-data-testid-attributes-in-react-components-769ab37442a9?source=rss-83191ece38e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/769ab37442a9</guid>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[enzyme]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[snapshot-testing]]></category>
            <dc:creator><![CDATA[Asís García]]></dc:creator>
            <pubDate>Mon, 12 Oct 2020 08:01:07 GMT</pubDate>
            <atom:updated>2020-10-12T08:01:07.694Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rr60M3OHUvhZ5hJgstmS5g.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@jens_johnsson?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Jens Johnsson</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Adding a data-testid attribute as a way to identify a DOM node for testing purposes, is a common tool recommended by many (<a href="https://testing-library.com/docs/dom-testing-library/intro">testing-library</a>, <a href="https://docs.cypress.io/guides/references/best-practices.html#Selecting-Elements">cypress</a>) as it decouples the DOM structure of your application from its tests.</p><p>When working with React, setting a data-testid on a DOM node (a host component) is easy: you just… set it 😅</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8f063599abdc0ff3f17d76b5ae30641/href">https://medium.com/media/c8f063599abdc0ff3f17d76b5ae30641/href</a></iframe><h3>Defining test ids for your components</h3><p>React is all about components, right? So, how do you set a data-testid inside a DOM node rendered by a component? Well, you have to pass a prop. You can name the prop data-testid, but then you’ll not be able to destructure that prop as a parameter of your component, so my advice is to name it testId.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/34747babc610f0954c5ed84aae183640/href">https://medium.com/media/34747babc610f0954c5ed84aae183640/href</a></iframe><p>That is a pretty silly component, rendering just a div with its test id. Most of the time you create components with a more complex structure. The problem is, if you want to refer to different parts of that structure through a test id, how do you do it?</p><p>There are two options:</p><ol><li>You pass a “map” of test ids in the testId prop, instead of a string. You use different keys for each part of the component you want to identify, and the value associated with each key as a data-testid for each DOM node.</li><li>You “derive” new test ids from the one provided via the testId prop.</li></ol><p>The first option is more explicit, but also more cumbersome to use. Think of a really complex component, like a data grid with many columns, rows and controls. In that case you may need to specify dozens of test ids in order to access every part of such a component.</p><p>The second option gives the “user” of your component less control, but it’s much easier to use: you just give the whole component a test id and derive from it different data-testid attributes for each part:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/13c5f29b2a16ab134804c07870ab6146/href">https://medium.com/media/13c5f29b2a16ab134804c07870ab6146/href</a></iframe><h3>Testing your test ids</h3><p>This is kind of meta, but if you’re developing components for others to use, you might want to test that you are setting the right test ids for your component.</p><h4>Using selectors</h4><p>One option is to use selectors: you find each node using a [data-testid=”the-id”] selector and assert that it exists. This is a simple option, and it lets you test that each test id is in place, but it tells you nothing about <em>where</em> you are setting those ids.</p><h4>Using snapshots</h4><p>Using a snapshot lets you check that every test id is being set, and it also lets you know on which node you set each test id. The problem is, snapshots are quite noisy, and you might have a hard time finding the test ids in the middle of all the other stuff.</p><h4>Using custom snapshots</h4><p>You can overcome the noise customizing the value to snapshot.</p><p>In the following snippet we define a keepTestId function which strips everything from the JSON representation of an <a href="https://enzymejs.github.io/enzyme/">enzyme</a> wrapper, except for the data-testid, class and className props:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7eb39d76f4ce01bf8a1748e09705a6ca/href">https://medium.com/media/7eb39d76f4ce01bf8a1748e09705a6ca/href</a></iframe><p>You can use it to test the “test id structure” of your components. We keep the class attributes so it’s easier to identify each node in the snapshot, specially when the component is complex, but you could choose to remove them and just keep the data-testid.</p><p>Given our Accordion component, we could test its structure with a test like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ba58c03edc68d0585748e1b8376757f/href">https://medium.com/media/2ba58c03edc68d0585748e1b8376757f/href</a></iframe><p>That will result in the following snapshot being written:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f76d1ac92aa235ce86ef89005ac2fd0a/href">https://medium.com/media/f76d1ac92aa235ce86ef89005ac2fd0a/href</a></iframe><p>As you can see, the output is barebone. Say we change the component to wrap the details inside a h1 element:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6033e8390fd23f73d9d36d846f2c4f4a/href">https://medium.com/media/6033e8390fd23f73d9d36d846f2c4f4a/href</a></iframe><p>The test ids snapshot will stay the same.</p><p>Snapshot testing has a bad reputation for leading to brittle tests, and for snapshots being easily overlooked when doing code reviews, but I find that in cases like this one, where the “spatial” information is important (I want to know where I set the test ids), they are the way to go. Specially if you adapt them to your specific needs, as we’ve seen in this story.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=769ab37442a9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/trabe/use-enzyme-jest-snapshots-to-test-data-testid-attributes-in-react-components-769ab37442a9">Use Enzyme &amp; Jest Snapshots to Test data-testid Attributes in React Components</a> was originally published in <a href="https://medium.com/trabe">Trabe</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fine-tune Dependency Versions in Your JavaScript Monorepo]]></title>
            <link>https://medium.com/trabe/fine-tune-dependency-versions-in-your-javascript-monorepo-1fa57d81a2de?source=rss-83191ece38e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fa57d81a2de</guid>
            <category><![CDATA[monorepo]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[node-modules]]></category>
            <category><![CDATA[yarn]]></category>
            <dc:creator><![CDATA[Asís García]]></dc:creator>
            <pubDate>Mon, 22 Jun 2020 08:01:00 GMT</pubDate>
            <atom:updated>2020-06-22T08:01:00.948Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CqN-9GJ4ufFYjMuAbCJQnA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@thesollers?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Anton Darius</a> on <a href="https://medium.com/s/photos/abstract?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>We’ve written before about <a href="https://medium.com/trabe/monorepo-setup-with-lerna-and-yarn-workspaces-5d747d7c0e91">how we use Yarn workspaces and Lerna</a> to setup monorepos. In this post I want to focus on how we solve the problems caused when different packages in the monorepo depend (directly or transitively) on different versions of the same dependency.</p><h3>A real-world scenario</h3><p>One of our projects is a monorepo with 8 different packages. One of those packages provides tooling to format JavaScript code using <a href="https://prettier.io/">Prettier</a>, version 1.19.1, and also to check the code formatting using <a href="https://prettier.io/docs/en/integrating-with-linters.html#eslint">ESLint</a>. That tooling is provided to the end users (so we must treat it as part of our public API), and we also use it to format and lint the code in the monorepo.</p><h4>An unwanted (but “compatible”) upgrade</h4><p>Our problems start when we add <a href="https://github.com/gregberge/svgr">SVGR</a> as a new dependency to one of our packages (a library of React components). We use SVGR as a CLI tool to generate React components from SVG files. To format the generated code, SVGR uses Prettier, so it depends on it.</p><p>The next image shows the relevant parts of our dependency tree:</p><figure><img alt="“components” package depends on SVGR, which depends on Prettier 2.0.2 or 1.9.1. Our “tools” package depends on version 1.9.1." src="https://cdn-images-1.medium.com/max/656/1*zTYHCGkFI430neiN9L15xw.png" /><figcaption>The two “conflicting” Prettier dependencies.</figcaption></figure><p>Although <a href="https://github.com/gregberge/svgr/blob/v5.3.1/packages/plugin-prettier/package.json">the package.json file</a> in SVGR declares a dependency with prettier@^2.0.2 or prettier@^1.9.1, Yarn always hoists prettier@2.0.2 to thenode_modules directory in the root of the monorepo, and installs prettier@1.9.1 at the tools package level:</p><figure><img alt="prettier@2.0.2 gets hoisted to the root node_modules, while prettier@1.9.1 is installed inside the “tools” node_modules." src="https://cdn-images-1.medium.com/max/719/1*P1ef1mcjN13hhqKbOPmFJw.png" /><figcaption>The versions installed on disk.</figcaption></figure><p>Having “the wrong” version of Prettier in the root affects the version our code editors see, and we end up with a lot of problems due to automatic format on save: while the linter in our CI and our <a href="https://medium.com/trabe/taming-the-husky-db15632c106f">Husky</a> pre-push hooks uses prettier@1.9.1, our editors format the code with prettier@2.0.2.</p><p>We could fix that changing our dependency to prettier@2.0.2, right? The problem is that Prettier 2 introduces some breaking changes. Updating the version we use in our tooling would force us to release a new major version of our packages, and our users to reformat their code. And we can’t do that 😅, so we’re stuck with v1.9.1.</p><h4>Using Yarn “resolutions”</h4><p>Yarn’s <a href="https://classic.yarnpkg.com/en/docs/selective-version-resolutions/">selective version resolutions</a> feature lets you override the version used for a given dependency. You just need to add a resolutions field to your package.json file.</p><p>So, to fix our problem, we update our rootpackage.json adding:</p><pre>// package.json<br>&quot;resolutions&quot;: {<br> &quot;prettier&quot;: &quot;1.9.1&quot;<br>}</pre><p>After doing that, our project will end up with a single version of Prettier (v1.9.1) installed at the root level, fixing our problems while still making SVGR happy. Yay! 🎉</p><h4>An unwanted (and “incompatible”) upgrade</h4><p>Now the problem appears after adding Storybook 6 (beta) as a dependency in our docs package:</p><figure><img alt="The dependency tree, adding a docs package which depends on Storybook, which in turn depends on Prettier ^2.0.5." src="https://cdn-images-1.medium.com/max/941/1*f8gE1ozE26DH14t4n2x_pw.png" /><figcaption>The new dependency tree after adding storybook.</figcaption></figure><p>Storybook depends on Prettier version ^2.0.5, but we’re overriding that dependency and forcing prettier@1.9.1. This causes Storybook to complain, as it tries to use a feature that does not exist in older versions of Prettier.</p><h4>Using Yarn “nohoist”</h4><p>If we remove the resolutions field, Yarn will fallback to the default resolution mechanism. As we saw in the previous section, we would end up with prettier@2.0.5 installed in the root node_modules directory, but we need prettier@1.9.1 there.</p><p>Enter <a href="https://classic.yarnpkg.com/blog/2018/02/15/nohoist/">nohoist</a>. With it, you can tell Yarn to stop hoisting some dependencies to the project root, keeping them installed as local dependencies where they are required.</p><p>To configure it, you have to use the workspaces.nohoist field in your root package.json file. In our project we want to prevent the Prettier versions required by Storybook (in the docs package) and SVGR (in the components package) from being hoisted, so we add the following configuration to our package.json:</p><pre>// package.json<br>{<br>  &quot;private&quot;: true,<br>  &quot;workspaces&quot;: {<br>    &quot;packages&quot;: [&quot;packages/*&quot;],<br>    &quot;nohoist&quot;: [<br>      &quot;docs/**/prettier&quot;,<br>      &quot;docs/**/prettier/**&quot;,<br>      &quot;components/**/prettier&quot;,<br>      &quot;components/**/prettier/**&quot;<br>    ]<br>  }<br>...<br>}</pre><p>The nohoist field must contain a list of nohoist rules. Each one of them is a <a href="https://en.wikipedia.org/wiki/Glob_(programming)">glob pattern</a> that will match against virtual paths in the dependency tree. For example, the full “path” to the Prettier dependency in SVGR is:</p><figure><img alt="Dependency tree: components depends on @svgr/cli, which depends on @svgr/plugin-prettier, which depends on prettier" src="https://cdn-images-1.medium.com/max/304/1*gt1YF1D5mMGpdF8xAFqNHQ.png" /><figcaption>Virtual path to the prettier dependency</figcaption></figure><p>Using yarn why &lt;package&gt;, you can see which versions of a given package are installed. Yarn will tell you for each installed version, which other packages caused that version to be installed. You can use that information to determine the “path” to a problematic dependency.</p><p>The nohoist value shown above tells Yarn not to hoist Prettier (nor any of its dependencies) when the dependency comes from the components or the docs package. That way, yarn will only hoist the version from our tools package, again solving our problems 😃.</p><p>The other versions of Prettier will be installed in thenode_modules directories inside the packages requiring them:</p><figure><img alt="Root node_modules layout. prettier@1.9.1 is installed at the root level, other versions inside internal node_modules." src="https://cdn-images-1.medium.com/max/1024/1*V5s8R1WeB1ovNXwBGtX9sQ.png" /><figcaption>The final layout inside the node_modules directory at the project root. The layout is simplified (it does not reflect the real layout of svgr or storybook packages).</figcaption></figure><h3>Summing up</h3><p>The sheer number of dependencies per node package, and the fast evolution of many of them, can easily lead to conflicting dependencies. Given the flexibility of node’s resolution mechanism, and the way Yarn workspaces uses it, sometimes you might end up with the wrong dependency being installed.</p><p>In this post we’ve seen how using Yarn’s resolutions and nohoist mechanisms, you can tweak the resolution algorithm, and hopefully fix your problems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fa57d81a2de" width="1" height="1" alt=""><hr><p><a href="https://medium.com/trabe/fine-tune-dependency-versions-in-your-javascript-monorepo-1fa57d81a2de">Fine-tune Dependency Versions in Your JavaScript Monorepo</a> was originally published in <a href="https://medium.com/trabe">Trabe</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An HTML Ruler With Vanilla JavaScript]]></title>
            <link>https://medium.com/trabe/an-html-ruler-with-vanilla-javascript-8d75ef9ffc8b?source=rss-83191ece38e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d75ef9ffc8b</guid>
            <category><![CDATA[rulers]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[measurement]]></category>
            <dc:creator><![CDATA[Asís García]]></dc:creator>
            <pubDate>Mon, 08 Jun 2020 08:01:02 GMT</pubDate>
            <atom:updated>2020-06-08T08:01:02.449Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ReruUz6zh1II17j3kF7c9A.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@sernarial?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">patricia serna</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>For one of our projects, we have to update a bunch of preexisting React components to make them match a redesign given in Figma. This implies having to adjust margins, paddings, and relative positions, making the “real” components a pixel-perfect replica of the “designed” ones.</p><p>The problem with pixel-perfect stuff is that you have to measure your components by the pixel. And pixels are tiny 😅. So, I find myself creating “ruler” divs many times a day. Whenever I need to check some distance or size, I have to open the developer tools, edit some component’s HTML, add a new div and then set some styles on it:</p><pre>position: absolute;<br>left: 0;<br>top: 0;<br>width: 4px;<br>height: 40px;<br>background: lime;</pre><p>With that ruler div in place, then I tweak its position and size, and use it to check for margins, paddings, and alignment issues.</p><p>But that feels really tedious, so I’ve decided to automate the process. And yes, I know there are some ruler extensions in the Chrome Web Store. In fact, I’ve used a ruler extension in the past, but <a href="https://medium.com/@poila/page-ruler-is-no-longer-a-viable-chrome-extension-due-to-the-fact-that-it-has-malware-js-see-8896a01a4441">I had to uninstall it</a>. I don’t want to go the extension way again, so I will build the ruler myself.</p><p>Also, I see this as an opportunity to build something simple but useful — at least for me — and to do it using vanilla JavaScript: no transpilers, no loaders, no bundlers, no BS (Build Step, of course).</p><h3>First step: enough with the repetition</h3><p>As I’ve said, I’m inserting the ruler manually. So the first step is to automate creating and styling the div, and then inserting it into the document:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cff5733d78409138bf53733ccacaec5b/href">https://medium.com/media/cff5733d78409138bf53733ccacaec5b/href</a></iframe><p>In the snippet above, the ruler function creates a new div element. The ruler will appear as a semi-transparent red square centered on the page.</p><p>The function returns a function to remove the ruler from the page. The snippet ends with a trick so it can be evaluated many times, each time removing the old ruler and creating a new one (this way I can keep tweaking the implementation easily).</p><h3>Second step: move the ruler around</h3><p>OK, now inserting the ruler is straightforward. But positioning it next to the element to be measured still needs some manual tweaking of the ruler style.</p><p>My first instinct is to use the mouse to drag the ruler into position, so I will add some event handlers:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee23db1945877548d0e34f036351e8ec/href">https://medium.com/media/ee23db1945877548d0e34f036351e8ec/href</a></iframe><p>First things first: in order for the ruler to be draggable, its draggable attribute must be set to true. Then, <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API">the drag &amp; drop API</a> events are used to move the ruler:</p><ol><li>When the dragstart event is fired on the ruler, the distance between the mouse and the ruler top left corner is captured. We can use it once the drag ends to determine how much to move the upper left corner of the ruler element. We store it as a JSON string, using the <a href="https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer/setData">setData</a> method.</li><li>The dragover event handler is attached to the document, because it’s mandatory for an element to act as a drop target (and we want to drop our ruler anywhere in the document).</li><li>Once the drag operation finishes, the drop event is fired and the event handler in the document updates the ruler position. We get the mouse offset position from the dragstart event and we parse it. The final ruler position (that is, its top left corner position) is calculated as the position of the mouse where the drop event fires minus the stored offset.</li></ol><p>We also update the removeRuler function to get rid of any event handler once the ruler is gone:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e7dd0c42ec0fae3e37966a3e5402415d/href">https://medium.com/media/e7dd0c42ec0fae3e37966a3e5402415d/href</a></iframe><h3>Third step: resize the ruler</h3><p>Now we can add and remove a ruler, and also move it around using the mouse. The only thing that’s left to do is resizing the ruler, as we still have to do it manually through the developer tools.</p><p>For this we are going to use the keyboard, so we need to add a keydown event handler to the ruler element. But for the element to be able to process keyboard events, it has to be focused. So we start by setting a tabIndex and giving the ruler the focus just after it is inserted in the page, and also when clicked:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f6f01593ba739d21ff8388352fcafb0/href">https://medium.com/media/9f6f01593ba739d21ff8388352fcafb0/href</a></iframe><p>Now we can define the event handler. And, because adjusting the position of the ruler using the mouse is hard when you need precision, I decided to let the user move the ruler using the keyboard too:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/caff9a8e6b08b153d4b17356c181db54/href">https://medium.com/media/caff9a8e6b08b153d4b17356c181db54/href</a></iframe><p>When the user presses one of the cursors or the Vim movement keys (h, j, k, and l), we check whether the control key is also pressed. If it is pressed, we update the ruler size. Otherwise, we update its position.</p><p>There is a goodie in there: if the user is holding the shift key, we use 10px increments to resize or move the ruler.</p><p>The changeSize and changePosition functions look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8a92fec575383d6696dfd65129d7256/href">https://medium.com/media/a8a92fec575383d6696dfd65129d7256/href</a></iframe><p>We also update the removeRuler function to get rid of the event handler (I know, there’s no need for the handler to be removed, as we are also removing the ruler element, but I prefer being consistent 🤷‍♂):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/93c42322ef2c1dad7f2cb912c73a3674/href">https://medium.com/media/93c42322ef2c1dad7f2cb912c73a3674/href</a></iframe><h3>Fourth step: getting feedback</h3><p>We can insert a ruler element, move it around with the mouse and move it and resize it using the keyboard. The only thing that’s left is knowing what is the size of the ruler. That’s an important thing, because a ruler without marks is mostly useless 😅.</p><p>To do this, we will set the ruler title attribute, so if the mouse stops over the ruler, its size will be displayed in a tooltip. But this is a slow and sometimes frustrating UI, so we will also add a keyboard shortcut to print the size to the console.</p><p>First, we define some functions to display the ruler information:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2453ed9f1e127a6ce3dd7c8bd0e2adbc/href">https://medium.com/media/2453ed9f1e127a6ce3dd7c8bd0e2adbc/href</a></iframe><p>Then we update changeSize so that every time the ruler is resized the title is updated and the information logged to the console:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e4eada357dca6ed2a6c9ec4e0fe5ba8/href">https://medium.com/media/7e4eada357dca6ed2a6c9ec4e0fe5ba8/href</a></iframe><p>We update the ruler keydown handler, so we can force the current size to be logged to the console pressing the i key:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8caa35f7c0374e20f46a828ca9826cf/href">https://medium.com/media/a8caa35f7c0374e20f46a828ca9826cf/href</a></iframe><h3>Final touches: minor improvements and launching the snippet</h3><h4>Minor improvements</h4><p>The <a href="https://gist.github.com/asis/e288290634bd1e94740ce74374aee766">final code</a> includes some minor improvements:</p><ol><li>The ruler has a “tracking mode” that can be toggled pressing the t key. When it is enabled, the ruler will follow your mouse, so you don’t need to find it and drag it.</li><li>The ruler can be “rotated” by pressing the r key (this will switch the width and height dimensions).</li><li>The ruler can be removed by pressing the Esc key.</li></ol><h4>Launching the snippet</h4><p>If you are using Chrome, it turns out that you can <a href="https://developers.google.com/web/tools/chrome-devtools/javascript/snippets">save and run snippets of JavaScript</a> from the Command Menu. So I just created a new snippet called “ruler”, I pasted the snippet code, and now I can insert a ruler inside the page just typing cmd-o and then !ruler&lt;enter&gt; 😃.</p><p>That’s it: using a pinch of CSS and some event handlers I’ve built my own HTML ruler. I hope you find it as useful as I do.</p><p>And now, back to the Build Step 😅.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d75ef9ffc8b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/trabe/an-html-ruler-with-vanilla-javascript-8d75ef9ffc8b">An HTML Ruler With Vanilla JavaScript</a> was originally published in <a href="https://medium.com/trabe">Trabe</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Custom useStateMachine React Hook]]></title>
            <link>https://medium.com/trabe/a-custom-usestatemachine-react-hook-5cd1dd9947c1?source=rss-83191ece38e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/5cd1dd9947c1</guid>
            <category><![CDATA[state-machine]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[xstate]]></category>
            <dc:creator><![CDATA[Asís García]]></dc:creator>
            <pubDate>Mon, 06 Apr 2020 08:01:00 GMT</pubDate>
            <atom:updated>2020-04-06T08:01:00.753Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rHkQmQ8PW8BQbcqdUPEKDw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@cakirchoff?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Chad Kirchoff</a> on <a href="https://unsplash.com/s/photos/engine?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>In his post <a href="https://kentcdodds.com/blog/stop-using-isloading-booleans">Stop using isLoading booleans</a>, <a href="https://medium.com/u/db72389e89d8">Kent C. Dodds</a> tells us to… well, to stop using booleans to keep track of binary states 😅. The problem with using a boolean flag to model our component’s state is that, usually, the flag is just part of a bigger, more complex state.</p><p>When you encode your component’s state in a bunch of binary flags, you end up rendering with a lot of conditional checking. That leads to code that is really difficult to maintain and extend.</p><p>Instead of using boolean values, Kent recommends using a <a href="https://en.wikipedia.org/wiki/Finite-state_machine">state machine</a>. In his post he uses <a href="https://github.com/davidkpiano/xstate">xstate</a>, a fully-fledged state machine library.</p><p>In this story I will offer a simpler alternative implemented as a Custom Hook using useReducer.</p><p>Of course, because it is simpler, this alternative is also less powerful, so if you are building a complex component, give xstate a try!</p><h3>Defining useStateMachine</h3><p>Quoting the Wikipedia, a state machine (or finite state machine, FSM) is</p><blockquote>[…] an abstract machine that can be in exactly one of a finite number of <em>states</em> at any given time. The FSM can change from one state to another in response to some inputs; the change from one state to another is called a <em>transition</em>. An FSM is defined by a list of its states, its initial state, and the inputs that trigger each transition</blockquote><p>So, in order to build our own state machine we need:</p><ol><li>A list of states.</li><li>A list of events (inputs).</li><li>A list of transitions (current state + event =&gt; next state. 🤔 this one looks familiar…).</li></ol><p>We are going to start designing the API for our useStateMachine custom Hook. What we want is something like this:</p><pre>const [currentState, sendEvent] = useStateMachine(machineSpec);</pre><p>The Hook accepts a machine specification object defining the states, inputs and transitions, and returns the current state and a method to send an event to the machine, to make it change (transition) to its new state.</p><p>Say we want to use a state machine to handle the connection to some remote service. Our user starts disconnected, and we want to let her connect to the service and disconnect from it. We can represent that machine like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9dc2c64740861c29d051d38ce1a23f59/href">https://medium.com/media/9dc2c64740861c29d051d38ce1a23f59/href</a></iframe><p>The spec encodes all the information needed to run the machine:</p><ol><li>The list of states, corresponding to the keys of the states property.</li><li>The list of transitions, defined for each state using EVENT_NAME: “nextState” pairs.</li><li>The initial state, so we know what to do when the first event is received.</li></ol><p>We can use that information to define our custom Hook:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c31c91d8fda90a40b174c25e80a8a29/href">https://medium.com/media/5c31c91d8fda90a40b174c25e80a8a29/href</a></iframe><p>As you can see, our custom Hook is just a special case of useReducer: given the spec, we use the state transitions in the states property to build a reducer function, and the initialState as the reducer’s initial state. The return value of useReducer meets our API requirements: we get the current state and a function to send (dispatch) events that will, in turn, update the machine’s state 😀.</p><h3>Using useStateMachine</h3><p>Now we can use our custom Hook to “drive” our application rendering and interactions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/805ff484dffe339be4e78e7f9d59b719/href">https://medium.com/media/805ff484dffe339be4e78e7f9d59b719/href</a></iframe><p>For each possible state, a different component is rendered. Each component receives a set of callbacks to send events to the state machine and uses those callbacks to handle the user interaction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*QvMoMEsfh75GvPCq44jHug.gif" /></figure><h3>Testing</h3><p>useStateMachine is just a glorified useReducer, so it’s pretty easy to test. You can extract your state machine to your own custom Hook and test it using testing tools like <a href="https://github.com/testing-library/react-hooks-testing-library">react-hooks-testing-library</a>. Or you can test the reducer function itself:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f615eed01a71f94582719bce2b38ccfc/href">https://medium.com/media/f615eed01a71f94582719bce2b38ccfc/href</a></iframe><h3>Maintenance</h3><p>The great thing about using a state machine is that the spec encodes every possible state of your component, and also every valid transition from state to state. This makes adding new states and transitions really simple.</p><p>Let’s modify our example to take into account possible connection errors. Now our state machine looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a38fedc8047b1c327265bf04f0bac7b/href">https://medium.com/media/5a38fedc8047b1c327265bf04f0bac7b/href</a></iframe><p>Now, while we are in the connecting state, we can receive a CONNECTION_ERROR event and transition to the error state. When in the error state, we can try to CONNECT again.</p><p>We update our components to handle the new state:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35822a2b4968be0cbe93a20407bbcbe6/href">https://medium.com/media/35822a2b4968be0cbe93a20407bbcbe6/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*s4g2VeYDebBv6Ch7Z9A34w.gif" /></figure><p>State machines are a very powerful tool for designing UI components. As we’ve seen in this story, even a naive implementation can be really helpful. You can start with something like this, and then, if you need to, go the full-blown-state-machine way and add transition guards, effects, nested machines, and all the other goodies that libraries like <a href="https://xstate.js.org/docs/">xstate</a> offer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5cd1dd9947c1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/trabe/a-custom-usestatemachine-react-hook-5cd1dd9947c1">A Custom useStateMachine React Hook</a> was originally published in <a href="https://medium.com/trabe">Trabe</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dealing With Git Conflicts Using Vim and Vcs-jump]]></title>
            <link>https://medium.com/trabe/dealing-with-git-conflicts-using-vim-and-vcs-jump-4ab1316e4271?source=rss-83191ece38e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ab1316e4271</guid>
            <category><![CDATA[vim]]></category>
            <category><![CDATA[workflow]]></category>
            <category><![CDATA[plugins]]></category>
            <category><![CDATA[merge]]></category>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[Asís García]]></dc:creator>
            <pubDate>Mon, 20 Jan 2020 09:01:02 GMT</pubDate>
            <atom:updated>2020-01-20T09:01:02.212Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Blue, red and orange liquids merging over a black background" src="https://cdn-images-1.medium.com/max/1024/1*h43FHvUemgag27Lbs5nilg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@aznbokchoy?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Lucas Benjamin</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p><a href="https://github.com/wincent/vcs-jump">vcs-jump</a> is a Vim plugin created by Greg Hurrell that “allows you to jump to useful places within a Git or Mercurial repository: diff hunks, merge conflicts, and grep results”.</p><p>I find it specially useful to resolve <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/about-merge-conflicts">merge conflicts</a> when rebasing or merging branches in git repos. Before I discovered this plugin, my merge/rebase workflow used to look like this:</p><ol><li>Run git checkout my-feature-branch.</li><li>Run git rebase master.</li><li>Get a CONFLICT warning 😖.</li><li>Run git status to clearly see which files have merge conflicts (I know they are listed when the rebase fails, but the output is so bloated with info messages that I get overwhelmed).</li><li>Open Vim, open the first conflicted file, search for the first conflict marker, fix the conflict, then search for more conflicts. Once I’m done with the current file, open the next one and repeat.</li><li>Close Vim and run git status again, check the list of conflicted files and try to guess if I’ve resolved every conflict 🤷‍♂️. If I see a file which I know I didn’t fix, I go back to 5.</li><li>Run git add -u &amp;&amp; git rebase --continue.</li></ol><p>Usually at step 5, once I fix the conflicts in the first file, I can’t remember the next file name, so I start to go back and forth between steps 4 and 5. Also, when I have to resolve a complex conflict, I sometimes forget that the current file might have additional conflicts and I forget to search for the next conflict marker. So I find myself revisiting files and searching for conflict markers again 😅.</p><h3>Enter vcs-jump</h3><p>I discovered vcs-jump watching <a href="https://www.youtube.com/watch?v=zKwsWIMfs24">one of Greg’s Vim screencasts</a> (if you use Vim, check his <a href="https://www.youtube.com/channel/UCXPHFM88IlFn68OmLwtPmZA">YouTube channel</a>, he’s uploaded lots of really interesting videos!), and I immediately saw how it would improve my git rebase workflow.</p><p>So I <a href="https://github.com/wincent/vcs-jump#installation">installed it</a> and, to streamline my rebasing sessions even more, I created a fish shell abbreviation, vimerge, which expands to vim -c ‘VcsJump merge’ (in plain English: “open Vim and run the `VcsJump merge` command”).</p><p>Now my work flow looks like this:</p><ol><li>Run git checkout my-feature-branch.</li><li>Run git rebase master.</li><li>Get a CONFLICT warning 😖.</li><li>Run vimerge. This opens the first conflicted file and populates Vim’s <em>quickfix</em> list with the location of each conflict marker in every file 😀. The <em>quickfix</em> window has the focus, so I just hit enter and then my cursor moves to the first conflict in the first file 🙌.</li><li>Resolve the conflict. Every time I want to go to the next one, I just run the :cnext command (or use Tim Pope’s <a href="https://github.com/tpope/vim-unimpaired">vim-unimpaired</a> mapping, ]q), until no more conflicts are left to fix.</li><li>Close Vim and run git add -u &amp;&amp; git rebase --continue (I’m sure I’ve resolved every conflict now! 😄).</li></ol><h3>Little things matter</h3><p>These might seem like a tiny improvement, but I can assure you that for me it’s been a game changer! I know it sounds far fetched, but resolving merge conflicts can get really tricky sometimes, and now I can focus on the actual conflict resolution and forget about the more mechanical part of the task (find the next conflict, the next file, check that every conflict has been resolved).</p><p>If you use Vim, give it a try. I hope you find it as useful as I do 🙂.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ab1316e4271" width="1" height="1" alt=""><hr><p><a href="https://medium.com/trabe/dealing-with-git-conflicts-using-vim-and-vcs-jump-4ab1316e4271">Dealing With Git Conflicts Using Vim and Vcs-jump</a> was originally published in <a href="https://medium.com/trabe">Trabe</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Keep two refs in sync using a custom React Hook]]></title>
            <link>https://medium.com/trabe/keep-two-refs-in-sync-using-a-custom-react-hook-c47c61e43e8f?source=rss-83191ece38e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/c47c61e43e8f</guid>
            <category><![CDATA[components]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[sync]]></category>
            <dc:creator><![CDATA[Asís García]]></dc:creator>
            <pubDate>Mon, 02 Dec 2019 09:01:01 GMT</pubDate>
            <atom:updated>2019-12-02T09:01:01.959Z</atom:updated>
            <content:encoded><![CDATA[<h3>Keep Two Refs in Sync Using a Custom React Hook</h3><figure><img alt="White arrow painted on a blue wall" src="https://cdn-images-1.medium.com/max/1024/1*DYTCPgq7yrE5lHgM_x-qvQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@jannerboy62?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Nick Fewings</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>When you need to get a <em>reference</em> to some component in a React application, you can use a <a href="https://reactjs.org/docs/refs-and-the-dom.html">ref</a>.</p><p>Whether you use a <a href="https://reactjs.org/docs/refs-and-the-dom.html#callback-refs">callback</a> or a ref object (created with either <a href="https://reactjs.org/docs/react-api.html#reactcreateref">createRef</a> or the <a href="https://reactjs.org/docs/hooks-reference.html#useref">useRef</a> Hook), you just need to attach the ref to a component’s ref prop and you are done:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be6751a13ee162fd49440aa78f2f66c6/href">https://medium.com/media/be6751a13ee162fd49440aa78f2f66c6/href</a></iframe><p>Now, suppose that the users of the Button component above want to get a ref to the DOM element.</p><p>You can use <a href="https://reactjs.org/docs/forwarding-refs.html#forwarding-refs-to-dom-components">forwardRef</a> to get the ref provided by the users:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/62457b599ba3ec5c14d233c2d60ab473/href">https://medium.com/media/62457b599ba3ec5c14d233c2d60ab473/href</a></iframe><p>But now you have a problem. What do you do with that ref? If you assign it to the button, you’ll break the auto-focus functionality. But if you don’t, your users will not get the ref they need.</p><p>Luckily, you can update the user provided ref once you own ref is updated:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f02440f5d758c1a7793b7b8a692919c/href">https://medium.com/media/9f02440f5d758c1a7793b7b8a692919c/href</a></iframe><p>The implementation above is pretty naive, as it will not work if the user provides a callback ref.</p><h3>Enter the useSyncedRef Hook</h3><p>We’ll define a custom Hook that will keep two refs in sync, like we did in the previous snippet, but taking into account the different types of refs:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59e2dd7f64d791a147f9d409ef702874/href">https://medium.com/media/59e2dd7f64d791a147f9d409ef702874/href</a></iframe><p>The custom Hook useSyncedRef takes a ref as a parameter and returns a new one. You can then use the returned ref, and the Hook will take care of keeping the original one in sync 🙂.</p><p>This story illustrates why I think Hooks are such an amazing addition to React: the way they compose, with so little friction, yet with so much power… custom Hooks are almost like a React-specific-DSL, and they make building React apps even more delightful than it already was 😄.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c47c61e43e8f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/trabe/keep-two-refs-in-sync-using-a-custom-react-hook-c47c61e43e8f">Keep two refs in sync using a custom React Hook</a> was originally published in <a href="https://medium.com/trabe">Trabe</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a lazy React components provider]]></title>
            <link>https://medium.com/trabe/creating-a-lazy-react-components-provider-bc93e0e14200?source=rss-83191ece38e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc93e0e14200</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[lazy-loading]]></category>
            <category><![CDATA[components]]></category>
            <category><![CDATA[provider]]></category>
            <dc:creator><![CDATA[Asís García]]></dc:creator>
            <pubDate>Mon, 11 Nov 2019 09:01:04 GMT</pubDate>
            <atom:updated>2019-11-11T09:01:04.081Z</atom:updated>
            <content:encoded><![CDATA[<h3>Creating a Lazy React Components Provider</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oNfSEWIxjI8YQAxUcgW-0g.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@lanceanderson?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Lance Anderson</a> on <a href="https://unsplash.com/s/photos/lazy-panda?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>In a previous story I wrote about <a href="https://medium.com/trabe/customizing-react-components-using-a-components-provider-42cdb78acd24">using a components provider to customize your components</a>. The code I shared in that story was a bit naïve (on purpose):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bed0481f3ea3900f776b6418f5ccc7ef/href">https://medium.com/media/bed0481f3ea3900f776b6418f5ccc7ef/href</a></iframe><p>In this story I’ll try to tackle two problems that prevent the snippet above from being used in a production application.</p><h3>Context-triggered re-renders</h3><p>This first problem is not specific to a components provider, but a common issue that you must be aware of if you use <a href="https://reactjs.org/docs/context.html">React Context</a>.</p><p>When you provide a value via context to some consumers, React will re-render those consumers whenever the provided value changes. If the value you share is an object, like in the code above, you have to be specially careful: building the value using a literal will result in a new (different) object being shared on every render. This causes a re-render of the consumers, every single time the provider renders.</p><p>You can use the<a href="https://reactjs.org/docs/hooks-reference.html#usememo">useMemo</a> Hook to prevent this from happening (pay special attention to non-obvious object literals, like the one used as the default value when no custom components are passed to the provider 😉):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7cf949fe50f2c228bff70dc681e25c1d/href">https://medium.com/media/7cf949fe50f2c228bff70dc681e25c1d/href</a></iframe><p>My colleague <a href="https://medium.com/u/7d0f37159e6e">David Barral</a> wrote a story about <a href="https://medium.com/trabe/how-we-handle-react-context-e43d303a27a2">How we use React Context</a> that you can read for more context-related “good practices”.</p><h3>Code splitting</h3><p>The components provider, as shown in the previous snippets, statically imports every component it provides. This means that your bundler of choice will bundle the provider and all the components it provides in a single file. In some scenarios, this can be a performance problem (particularly if you provide lots of components).</p><p>Using <a href="https://reactjs.org/docs/code-splitting.html#reactlazy">React.lazy</a> you can overcome this problem: instead of providing the real components, the provider will expose lazy wrappers loaded via <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#Dynamic_Imports">dynamic imports</a> (at least for the less used or more “heavy” components):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f98fb195f8c6b1f9014f6ce639b78e9c/href">https://medium.com/media/f98fb195f8c6b1f9014f6ce639b78e9c/href</a></iframe><p>You can then use Suspense to wait while the lazy components are loaded:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a61404de0c4206af6860ff56071dbe6/href">https://medium.com/media/6a61404de0c4206af6860ff56071dbe6/href</a></iframe><p>And if you use a capable bundler (<a href="https://webpack.js.org/">Webpack</a>, <a href="https://parceljs.org/">Parcel</a>, <a href="https://rollupjs.org/guide/en/">rollup</a>), the lazy components will be downloaded on demand from a different bundle file 😄.</p><h4>Reducing the number of chunks</h4><p>If you use dynamic imports to load every component you might end up with too many “bundles” (one file per imported component). You can mitigate this scenario using a dynamic import for a single module and <em>cherry-picking</em> the components you want to expose:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/655697c6ca4ceecf89bcf3a9ba8155c2/href">https://medium.com/media/655697c6ca4ceecf89bcf3a9ba8155c2/href</a></iframe><p>In the example above I’m supposing that your project has many simple components to build forms, all exported from a single index file in the forms directory, and that you want all of them to be bundled together in a single file.</p><p>You can achieve that dynamically importing the whole directory and then exposing each individual component as a lazy-loaded one.</p><p>There is a problem, though. The forms/index.js file in the previous example exports a bunch of components as named exports, but React.lazy only works when the import promise returns a module with a component as a default export:</p><blockquote>React.lazy takes a function that must call a dynamic import(). This must return a Promise which resolves to a module with a default export containing a React component.</blockquote><p>So, you can’t do something like:</p><pre>checkbox: lazy(() =&gt; import(&quot;./forms&quot;).then(mod =&gt; mod.Checkbox)),</pre><p>You have to return a “fake module” with a “default export”:</p><pre>checkbox: lazy(() =&gt; import(&quot;./forms&quot;).then(mod =&gt; ({<br>  default: mod.Checkbox<br>})),</pre><h3>Wrapping up</h3><p>In this story we’ve seen how to use a couple of React’s tools (useMemo and lazy/Suspense) to enhance our components provider and make it more suitable for production use. Now it won’t cause unexpected re-renders, nor will it affect your bundle size 😀.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc93e0e14200" width="1" height="1" alt=""><hr><p><a href="https://medium.com/trabe/creating-a-lazy-react-components-provider-bc93e0e14200">Creating a lazy React components provider</a> was originally published in <a href="https://medium.com/trabe">Trabe</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Customizing React components using a components provider]]></title>
            <link>https://medium.com/trabe/customizing-react-components-using-a-components-provider-42cdb78acd24?source=rss-83191ece38e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/42cdb78acd24</guid>
            <category><![CDATA[provider]]></category>
            <category><![CDATA[theming]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[components]]></category>
            <dc:creator><![CDATA[Asís García]]></dc:creator>
            <pubDate>Mon, 21 Oct 2019 08:01:02 GMT</pubDate>
            <atom:updated>2019-10-21T08:01:02.046Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2sPgrTyQJExDt0H6JoJ5eQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@eprouzet?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Eric Prouzet</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>When we talk about component customization, we usually think of <em>style</em> <em>theming</em>: changing the way a component looks by adjusting its style properties, based on some global values (the <em>theme</em>).</p><p>In this story, however, I’ll be talking about a different level of customization. When you develop a UI library, some of the more complex components are created using other basic components (think a ConfirmationDialog using a Button). Sometimes letting the user change the style of the basic components deeply nested inside the more complex one is cumbersome; sometimes is just not enough: what if the user want’s to totally change the way a Button renders inside a ConfirmationDialog?</p><h3>Providing components</h3><p>You can use <a href="https://medium.com/trabe/how-we-handle-react-context-e43d303a27a2">React’s Context</a> functionality to create a provider of components for your library. This provider will act as a registry, where you associate each basic component with its implementation. You can then get those basic components from the registry, and use them to build the rest of the components. That way, you can change the look &amp; feel or the behavior of a basic component, even when it is deeply nested inside other components.</p><h4>A simple components provider</h4><p>The following code snippet shows a simple components provider:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82d78b7958b6c32b635cca7554a64f5e/href">https://medium.com/media/82d78b7958b6c32b635cca7554a64f5e/href</a></iframe><p>You can use the provider in your app like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6288eae527fab93e9bc6b2c728c5ec9c/href">https://medium.com/media/6288eae527fab93e9bc6b2c728c5ec9c/href</a></iframe><p>The Page component in the previous code snippet uses a custom useComponents hook to get some components from the provider. In this case there is no ComponentsProvider around the Page component, so it will use the default Button and Icon.</p><p>You can add aComponentsProvider to the App and change the provided components (line 23). This in turn will change the components used by Page:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d3ff1fd81257fcfed7bcdfc506ed8dc/href">https://medium.com/media/5d3ff1fd81257fcfed7bcdfc506ed8dc/href</a></iframe><h4>Cherry-pick component overrides</h4><p>In the previous examples you had to provide all the components every time you choose to use ComponentsProvider. Of course, that is not the best of the APIs. You can use spreading to let the user override just some of the default components:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bed0481f3ea3900f776b6418f5ccc7ef/href">https://medium.com/media/bed0481f3ea3900f776b6418f5ccc7ef/href</a></iframe><p>Now you can override the Icon component and use the default Button:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e999d8ecf0e9cb21f7d759eedf2eb096/href">https://medium.com/media/e999d8ecf0e9cb21f7d759eedf2eb096/href</a></iframe><h4>Meta-provided components</h4><p>You can provide components that in turn use other provided components to render themselves. The provided Button in the previous examples could be defined as:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/304e02dbd585ec8795d44badc16c1bc1/href">https://medium.com/media/304e02dbd585ec8795d44badc16c1bc1/href</a></iframe><p>We’re creating a cyclic dependency here (components-provider.jsx depends on button.jsx to provide the default Button implementation, which in turn depends on components-provider.jsx to get the Icon implementation), but thanks to <a href="https://2ality.com/2015/07/es6-module-exports.html#es6-modules-export-immutable-bindings">the way exports work in ES</a>, the module system has no problem resolving the dependencies at build time.</p><p>Using a provider like this, you can create libraries of components that are customizable beyond its styles, letting your users change the way basic components look, and also how they behave.</p><p>In this story I’ve shown you a naïve implementation of the provider, to make the core idea easier to grasp. In future stories we’ll see how to create a provider that you could use in real applications. Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42cdb78acd24" width="1" height="1" alt=""><hr><p><a href="https://medium.com/trabe/customizing-react-components-using-a-components-provider-42cdb78acd24">Customizing React components using a components provider</a> was originally published in <a href="https://medium.com/trabe">Trabe</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced composition in React: cloneElement, HOCs and renderProps]]></title>
            <link>https://medium.com/trabe/advanced-composition-in-react-cloneelement-hocs-and-renderprops-a20971aec50e?source=rss-83191ece38e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/a20971aec50e</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[render-props]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[hoc]]></category>
            <category><![CDATA[cloneelement]]></category>
            <dc:creator><![CDATA[Asís García]]></dc:creator>
            <pubDate>Mon, 02 Sep 2019 08:01:01 GMT</pubDate>
            <atom:updated>2019-09-02T08:01:01.310Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AhZJoG91cDsxbS9irPM-fg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@miklevasilyev?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Mikhail Vasilyev</a> on <a href="https://unsplash.com/search/photos/peek?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>In this story we’ll have a look at some advanced ways to compose React components, how they work and when to use them.</p><h3>cloneElement</h3><p>As you might know, you can pass rendered components through props (that’s what you are doing whenever you use children, anyway 🙂). You can even use that as a neat trick to <a href="https://kentcdodds.com/blog/optimize-react-re-renders">optimize your components</a>.</p><p>Once you get a rendered component, you can pass it new props using <a href="https://es.reactjs.org/docs/react-api.html#cloneelement">React.cloneElement</a>. This way, while it is up to whoever is using your component to decide what to render, you still get to customize the received component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5105a9c49f5e714326a4608b113fa12/href">https://medium.com/media/e5105a9c49f5e714326a4608b113fa12/href</a></iframe><p>In the example above, SecretNote uses cloneElement to inject a value into an element. SecretNote doesn’t know which component will be used to render its value. It gets a React element via props, it injects its value into that element, and finally it renders it.</p><p>The App component renders SecretNote and passes it a &lt;RedPen /&gt; element. This is a way of delegating the rendering of part of a component to its owner (SecretNote delegates to App how to render its “secret” text).</p><h4>Prop name contract</h4><p>This method needs a contract to exist between the component that provides the value and the one that will use it. In the example above, both SecretNote and RedPen use a prop named text. Sometimes this can be a problem, as the component you are cloning might use a different prop name, or use a prop with the same name for a totally different purpose. This means that you’ll need to adapt some components to use this pattern:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6bcbddb13a468e94e1619a7450de4d2/href">https://medium.com/media/b6bcbddb13a468e94e1619a7450de4d2/href</a></iframe><h3>Higher Order Component</h3><p>You can use a <a href="https://reactjs.org/docs/higher-order-components.html">Higher Order Component</a> to inject values into components. HOCs can be seen as component decorators: you give the HOC a component and it returns a new decorated component, that will render the original component with some additional props injected:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9fc76112fdffabb6509976a68d55de5b/href">https://medium.com/media/9fc76112fdffabb6509976a68d55de5b/href</a></iframe><p>withSecret is a HOC that, given a component Comp, returns a new component WrappedComponent. This new component renders Comp passing the “secret” text.</p><h4>Prop name contract</h4><p>The HOC solution, like the cloneElement one, also needs both the HOC function and the component it wraps to share a common prop name (text in the example). The same problems may arise when using “incompatible” components, and the same fix can be used:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06fc520b686ed6d4cbc2c6f5c88e4dfa/href">https://medium.com/media/06fc520b686ed6d4cbc2c6f5c88e4dfa/href</a></iframe><h3>Render props</h3><p>A <a href="https://reactjs.org/docs/render-props.html">render prop</a> is a function that your component invokes to get a React element, delegating part of its rendering. It’s similar to using cloneElement, but you give the component passing the render prop the ability to dynamically determine how to render:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5e5838a7f7fedc35901b9f3a0c4938d/href">https://medium.com/media/e5e5838a7f7fedc35901b9f3a0c4938d/href</a></iframe><h4>More flexibility</h4><p>This solution is more flexible than the previous ones. Using a render prop, you don’t have to worry about the “compatibility” between the component accepting the render prop and the component you want to render, because you will be rendering “on demand” when the render prop gets called:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/90a5a8dadfbc2db5ea1fe85a50d7b490/href">https://medium.com/media/90a5a8dadfbc2db5ea1fe85a50d7b490/href</a></iframe><h3>When to use each solution</h3><p>As you can see from the previous examples, all three solutions are very similar. In the end, what you can do using a render prop, you also can do using a HOC or cloning an element. For me, which method you use is a matter of API and taste :)</p><h4>cloneElement</h4><p>I prefer cloneElement when I am defining a component with a specific UI element which I want to let the user customize. Buttons are a common use case:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/96696edd75bf704343978c2c6877d76e/href">https://medium.com/media/96696edd75bf704343978c2c6877d76e/href</a></iframe><p>You can also use cloneElement to inject values into your child components when the parent-child relationship implies a shared API. Libraries like <a href="https://reach.tech/router">Reach Router</a> do <a href="https://github.com/reach/router/blob/master/src/index.js#L205">just that</a>.</p><h4>HOC</h4><p>Higher Order Components are very useful when you want to provide access to some data or some common behavior in a way that you can compose statically. Or, they <em>were</em> very useful. Nowadays, I’d only create HOCs in applications using React &lt; 16.8.0 🤷‍♂️. Also, they have some <a href="https://reactjs.org/docs/higher-order-components.html#caveats">caveats</a>.</p><p>Before <a href="https://reactjs.org/docs/hooks-intro.html">Hooks</a>, a typical usage of HOCs was sharing some complex behavior, usually involving some local state handling and/or lifecycle methods:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71b9d764e4e7b0b012b9b265dd25eb2f/href">https://medium.com/media/71b9d764e4e7b0b012b9b265dd25eb2f/href</a></iframe><p>(If you want to learn more about Hooks, and how they can replace HOCs, check <a href="https://medium.com/u/85c2933da91c">Ceci García García</a>’s latest stories).</p><h4>render props</h4><p>Render props give the user of your component total freedom when it comes to decide the way a part of your component is rendered. You could achieve the same effect using cloneElement, but cloneElement forces you to define and use a “fully fledged” component. What if you just want to add a simple wrapper around other component, or show two components side by side, without extracting any of that UI elements to its own component?</p><p>A render prop is almost like an anonymous React component… but it’s still not a component, as React just sees the result of calling it: a bunch of elements. Take the example we used when we talked about cloneElement:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5105a9c49f5e714326a4608b113fa12/href">https://medium.com/media/e5105a9c49f5e714326a4608b113fa12/href</a></iframe><p>Here React sees the following tree (notice the RedPen component):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*D6ady3OS3rSMSccouuGY5w.png" /><figcaption>Component tree when using cloneElement</figcaption></figure><p>But when you use the render prop:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5e5838a7f7fedc35901b9f3a0c4938d/href">https://medium.com/media/e5e5838a7f7fedc35901b9f3a0c4938d/href</a></iframe><p>React sees the following tree (no RedPen here):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*lFfkCPkA2Wid-aX4VjaNiQ.png" /><figcaption>Component tree when using a render prop</figcaption></figure><p>When using cloneElement, you have to wrap everything you want to render in a component (RedPen in the example), while the render prop pattern lets you just render what you want, without the need to define additional components. That’s why you should prefer render props when you want to give the developer using your components more freedom and ease of use.</p><p>Let’s revisit the DoubleSidedPanel example. Suppose you don’t want to force the usage of something clickable to toggle the panel. You could use a render prop to inject the toggle callback and let the user decide how to use it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b98a7fe323b062677e16754d1441519f/href">https://medium.com/media/b98a7fe323b062677e16754d1441519f/href</a></iframe><p>Do you use any of this methods? Which one do you prefer? Why?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a20971aec50e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/trabe/advanced-composition-in-react-cloneelement-hocs-and-renderprops-a20971aec50e">Advanced composition in React: cloneElement, HOCs and renderProps</a> was originally published in <a href="https://medium.com/trabe">Trabe</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>