<?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 Adam Terlson on Medium]]></title>
        <description><![CDATA[Stories by Adam Terlson on Medium]]></description>
        <link>https://medium.com/@adamterlson?source=rss-583b3a685d22------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*g77atZ7fzoA8ZRAm.</url>
            <title>Stories by Adam Terlson on Medium</title>
            <link>https://medium.com/@adamterlson?source=rss-583b3a685d22------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 23:08:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@adamterlson/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[Migrating a Flow + React Native app to TypeScript]]></title>
            <link>https://medium.com/@adamterlson/migrating-a-flow-react-native-app-to-typescript-c74c7bceae7d?source=rss-583b3a685d22------2</link>
            <guid isPermaLink="false">https://medium.com/p/c74c7bceae7d</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[flow]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Adam Terlson]]></dc:creator>
            <pubDate>Wed, 09 Oct 2019 22:12:54 GMT</pubDate>
            <atom:updated>2019-10-22T16:21:13.612Z</atom:updated>
            <content:encoded><![CDATA[<h3>Migrating a 50K SLOC Flow + React Native app to TypeScript</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lgbUY9jRnV-0a61v" /><figcaption>Photo by <a href="https://unsplash.com/@sickle?utm_source=medium&amp;utm_medium=referral">Sergey Pesterev</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>“Well, it depends” is the prototypical response when asking a software engineer for advice, no matter how straight-forward the problem may seem. When asked “Should we choose TypeScript or Flow for our next React Native project?” however, the answer only depends on one variable: whether or not you work at Facebook.</p><p>It’s interesting to consider how we got here. The project team evaluated Flow vs TypeScript for our new React Native app almost three years ago. At the time, TypeScript didn’t support React well, didn’t allow for a gradual opt-in, there was no Babel support, and VSCode wasn’t the editor providing the best JavaScript development experience on the market.</p><p>None of these factors are true today. But why bother to migrate? TypeScript has a lot of value to offer making the switch highly attractive:</p><ul><li>More “future proof”</li><li>Higher OSS adoption &amp; better RN + library support</li><li>Awesome developer experience (VSCode)</li><li>Consistency with other department projects</li><li>Easier to hire for</li></ul><p>So, we forged ahead! But how’d it go?</p><h3>Before: 50K SLOC, 84% Flow Coverage</h3><pre>$ npx sloc app</pre><pre>---------- Result ------------<br>Physical :  57903<br>Source :  50859<br>Number of files read :  709<br>----------------------------</pre><pre>$ npx flow-coverage-report  -i &#39;app/**/*.js&#39;</pre><pre>percent: 84 %</pre><pre>$ time flow check<br>flow 3.64s user 2.31s system 32% cpu 18.458 total</pre><h3>Getting Started</h3><p>The first step we took was to update our JS tooling configuration. For our project, the procedure was relatively straight-forward, guided mostly by simply copying the configurations directly from a newly instantiated TypeScript template project using the <a href="https://facebook.github.io/react-native/docs/typescript">react-native cli</a>.</p><h4>Prettier &amp; ESLint</h4><pre>{<br>    &quot;parser&quot;: &quot;typescript&quot;<br>}</pre><p>One used to have to deal with TSLint when chosing TypeScript but thankfully <a href="https://github.com/palantir/tslint">TSLint is deprecated</a>, so it’s an easy choice in 2019—just stick with ESLint! Literally no changes necessary (for our usage anyway, and that included plugins and custom rules!)</p><p>Done. Next.</p><h4><em>Bonus Aside: Removing Black Magic module imports</em></h4><p>Did you know that you can import JavaScript modules relative to a package.json file using the name attribute in the json file, no plugins required?</p><p>Black magic! But it was useful black magic!</p><p>To accomplish absolute path imports (i.e. import Foo from ‘app/ui/components/Foo&#39;) we included in our project a package.json in the /app directory (and several others as well for a total of 4 package.json’s):</p><pre>{ &quot;name&quot;: &quot;app&quot; }</pre><p>This even works when importing from other folders in the tree (meaning you can import from app/components/Foo outside of the ‘app’ folder).</p><p>Well, TypeScript doesn’t like this black magic fuckery and couldn’t figure out our imports :(. So, we deleted our extra package.json files and chose to use babel instead.</p><h4>Babel</h4><p>With built in Babel support for TypeScript in Babel 7, converting our babel configuration from Flow to TypeScript was a process of simply removing unused plugins (like @babel/plugin-transform-flow-strip-types).</p><p>Here’s our final Babel.config.js, complete with less magical module resolution.</p><pre>module.exports = {<br>    presets: [&#39;module:metro-react-native-babel-preset&#39;],<br>    plugins: [<br>        [<br>            &#39;module-resolver&#39;,<br>            {<br>                root: [&#39;.&#39;],<br>                alias: {<br>                    app: &#39;./app&#39;<br>                },<br>            },<br>        ],<br>    ]<br>}</pre><h4>tsconfig.json</h4><p>While not strictly required for running your React Native app (Babel will just strip/ignore the TS syntax anyway), the tsconfig is required for using the TypeScript compiler (and VSCode tooling) to detect type errors.</p><p>Thankfully we got 90% of the way there by simply copy-pasting the tsconfig from a boilerplate new React Native project. However, we also include some .json files in our project, which require some additional configuration.</p><pre>{<br>  &quot;compilerOptions&quot;: {<br>    &quot;baseUrl&quot;: &quot;.&quot;,<br>    &quot;allowJs&quot;: true,<br>    &quot;allowSyntheticDefaultImports&quot;: true,<br>    &quot;esModuleInterop&quot;: true,<br>    &quot;isolatedModules&quot;: true,<br>    &quot;jsx&quot;: &quot;react-native&quot;,<br>    &quot;lib&quot;: [&quot;es6&quot;, &quot;dom&quot;],<br>    &quot;moduleResolution&quot;: &quot;node&quot;,<br>    &quot;noEmit&quot;: true,<br>    &quot;strict&quot;: true,<br>    &quot;target&quot;: &quot;esnext&quot;,<br>    &quot;resolveJsonModule&quot;: true, // Required for JSON files<br>    &quot;skipLibCheck&quot;: true<br>  },<br>  &quot;exclude&quot;: [<br>    &quot;node_modules&quot;,<br>    &quot;e2e&quot;,<br>    &quot;**/*.json&quot;, // Don&#39;t try and check JSON files<br>    &quot;**/*.spec.ts&quot;,<br>  ]<br>}</pre><h3>Migrating Flow to TS syntax and .js to .ts/x</h3><p>Thankfully some work has been done in the open source community to aid in the conversion from Flow to TypeScript syntax, and the projects have support for many of the common language features. However, I cannot say that these projects tend to be very well maintained or mainstream.</p><p>There are two dominant solutions available, <a href="https://github.com/bcherny/flow-to-typescript">flow-to-typescript</a> and <a href="https://github.com/Kiikurage/babel-plugin-flow-to-typescript">babel-plugin-flow-to-typescript</a>. We tried the flow-to-typescript library first but abandoned it because it crashed on any file containing a function (WTF?).</p><p>Thankfully the babel-plugin-flow-to-typescript worked for us. Almost.</p><p>As of writing the same <a href="https://github.com/Kiikurage/babel-plugin-flow-to-typescript/issues/36">bug</a> related to function support forced us to use <a href="https://github.com/zxbodya/babel-plugin-flow-to-typescript">a fork</a>. I don’t know what’s up with these tools and supporting plain old functions but whatever, it worked, I guess I should be thankful!</p><p>Convert JavaScript + Flow with a .js extension to TypeScript with .ts:</p><pre>yarn global add @babel/cli @babel/core babel-plugin-flow-to-typescript</pre><pre><em># Convert single file<br></em>npx babel script.js -o script.ts --plugins=babel-plugin-flow-to-typescript</pre><pre><em># Convert all files and delete original JS after conversion<br># Prereq: &#39;brew install parallel&#39;<br></em>find app -type f -name &#39;*.js&#39; | parallel &quot;npx babel {} -o {.}.ts &amp;&amp; rm {}&quot;</pre><blockquote>Note: We actually used @zxbodya/babel-plugin-flow-to-typescript due to a bug in the main repo.</blockquote><p>Next, rename any files which import React at the top to use .tsx instead:</p><pre>find app/components -name &quot;*.ts&quot; -exec sh -c &#39;git mv &quot;$0&quot; &quot;${0%.ts}.tsx&quot;&#39; {} \;</pre><h3>Sanity Check: Does the app still run?</h3><p>Before proceeding any further, it’s worth checking at this point that the project actually runs. Because Babel is used to compile TypeScript to JavaScript, and Babel simply strips out all TypeScript related syntax, regardless of how many type errors your project has it should “Just Work.”</p><p>In our case, it took less than half a day to update configurations, rename files, migrate all syntax, and get a running app again.</p><p>But the work is obviously still far from over.</p><h3>Fixing 1000s of compilation errors</h3><p>In our case, the effort began with ~1800 TS compilation errors.</p><p>Fixing this amount of errors is not a linear journey where one fix means your errors go down to 1799. Sometimes, making a change will result in dozens fewer errors, making you feel like a god among mortals, and sometimes it goes way up causing you to wonder if you can do anything right.</p><h4>#1—Fixing the Implicit Any</h4><p>The number one thing TypeScript will complain about is an implicit any. Mostly due to differences between TS and Flow regarding type inference, one must immediately add additional annotations.</p><p>Be warned: don’t go simply adding a type explicitly where TypeScript complains. Instead, ask “Why is this thing any?”</p><pre>// Problem here<br>const reqs = get(props, &#39;requests&#39;, [])<br>const inProgressIds = reqs.map(req =&gt; req.id)<br>const activeRequests = actions<br>    // Error shown here<br>   .filter(action =&gt; inProgressIds.includes(action.id))</pre><p>Rather than adding a type to action as the error suggests, reqs is missing a type, producing the error below. The root cause could be another issue in the function, or even an entirely different file!</p><h4>#2—Updating React components</h4><p>Easily the least enjoyable and most “hairy” part of the conversion is migrating React code. Errors thrown in React code often have long error chains, sometimes with details that seem at the surface totally unrelated to the required fix.</p><p>Our project limits the use of React Native primitives from our “smart” components, choosing instead to create our own set of primitives in a reusable UI framework.</p><pre>/* @flow */<br>import Button as RNButton from &#39;react-native&#39;</pre><pre>// Seal to avoid warning about inexact spread<br>type PropTypes = {|<br>    onPress: () =&gt; mixed,<br>    custom: boolean,<br>|}</pre><pre>// Trivialized component<br>const Button = (props: PropTypes) =&gt; &lt;RNButton {...props } /&gt;</pre><p>Under Flow, one must add every prop passed into &lt;Button&gt; to PropTypes, where instead we’d prefer to take all the props that &lt;RNButton&gt; does and add in our own custom one.</p><pre>// Import props available for every React Native component!  :D<br>import Button as RNButton, { ButtonProps } from &#39;react-native&#39;</pre><pre>interface PropTypes extends ButtonProps {<br>    custom: boolean,<br>}</pre><pre>const Button = (props: PropTypes) =&gt; &lt;RNButton {...props } /&gt;</pre><p>Much preferable (and accurate)! Interfaces are one of the best parts about TypeScript!</p><h4>#3—Refactoring HOCs</h4><p>One benefit gained with TypeScript over Flow is the ability to use generic type arguments inside the body of your function. Not sure how advisable generally this is, but it’s a great feature to have when adding types for higher order components!</p><pre>// TS allows the use of generics in the body of your HOC.  Yes!</pre><pre>const withAThing = &lt;T&gt;(config: Config&lt;T&gt;) =&gt; <br>    (WrappedComponent: React.ComponentType&lt;T&gt;) =&gt; <br>        (props: T) =&gt; &lt;WrappedComponent {...props } /&gt;</pre><p>However, in order to leverage this feature, we more-or-less needed to completely rewrite our type definitions for all of our higher order components. Ouch.</p><p>Needless to say we‘d prefer hooks!</p><h3>After: 96% TypeScript Coverage</h3><pre>$ type-coverage -p tsconfig.json # ignored tests + storybook</pre><pre>68712 / 71471 96.13%</pre><pre>$ time tsc<br>tsc  29.82s user 1.76s system 166% cpu 18.955 total</pre><p>Coverage increase of ~12%. Execution time more or less identical.</p><p>By far the most significant type coverage gaps exist in our Redux Saga code. This was true under Flow as well, but it seems switching to TypeScript hasn’t improved matters much, if any.</p><h3>Summary</h3><p>If you’re still using Flow with React Native, it’s never been easier to switch!</p><p>It took the equivalent of 3 engineers 10 working days to accomplish the conversion, including time taken for regression testing, code review, refactoring, and developing new usage patterns.</p><p>The majority of errors can be easily solved with a google search for the error message, while a few required time, consideration, and experience to be confident in the fix.</p><p>Though we discovered a few bugs (mostly related to incorrect third party API usage), this was a minor benefit to the effort. Gaining some additional coverage on our React code did allow for some dead code elimination.</p><p>Overall, we achieved a codebase better poised for ongoing future development both in community support and developer experience.</p><p>If you liked this article, follow me (<a href="https://medium.com/u/583b3a685d22">Adam Terlson</a>) on Medium and @adamterlson on Twitter! Please 👏 this article and share it elsewhere. Thank you for your support!</p><p>Twitter: <a href="https://twitter.com/adamterlson">@adamterlson</a><br>My latest talk: <a href="https://www.youtube.com/watch?v=sBbRQK58Fg8">Strangling Legacy with React Native</a></p><figure><a href="https://usejournal.com/?utm_source=medium.com&amp;utm_medium=noteworthy_blog&amp;utm_campaign=tech&amp;utm_content=guest_post_image"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PYxBP_WV7LI6zc-zdUkNqQ.png" /></a></figure><p>📝 Read this story later in <a href="https://usejournal.com/?utm_source=medium.com&amp;utm_medium=noteworthy_blog&amp;utm_campaign=tech&amp;utm_content=guest_post_read_later_text">Journal</a>.</p><p>👩‍💻 Wake up every Sunday morning to the week’s most noteworthy stories in Tech waiting in your inbox. <a href="https://usejournal.com/newsletter/noteworthy-in-tech/?utm_source=medium.com&amp;utm_medium=noteworthy_blog&amp;utm_campaign=tech&amp;utm_content=guest_post_text">Read the Noteworthy in Tech newsletter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c74c7bceae7d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Open response to “Tests > Types”]]></title>
            <link>https://itnext.io/open-response-to-tests-types-71e6c88b344b?source=rss-583b3a685d22------2</link>
            <guid isPermaLink="false">https://medium.com/p/71e6c88b344b</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[open-letter]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[debate]]></category>
            <dc:creator><![CDATA[Adam Terlson]]></dc:creator>
            <pubDate>Sun, 22 Sep 2019 18:44:48 GMT</pubDate>
            <atom:updated>2019-10-10T21:35:28.061Z</atom:updated>
            <content:encoded><![CDATA[<h4>TypeScript’s advantages over JavaScript are clear for all.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZyLh_E2hHt96aIHe" /><figcaption>Photo by <a href="https://unsplash.com/@bdchu614?utm_source=medium&amp;utm_medium=referral">Brendan Church</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>What follows is a response I wrote to a developer who had some rather bold claims about typed vs untyped JavaScript applications (and statically vs dynamically typed languages in general).</p><p>While I won’t try and reproduce the developer’s argument, the main points were roughly:</p><ul><li>Any time spent adding types to JavaScript code is better spent writing tests.</li><li>There is no value that types bring to developing JavaScript applications that cannot be better achieved in some other way.</li><li>Library authors and the community do not benefit from publishing type definitions with for their libraries.</li></ul><p>The first two paragraphs of my letter directly addresses this article which was sent to me as evidence that statically typed languages are not superior to dynamic ones. You can read the article here: <a href="https://danluu.com/empirical-pl/">https://danluu.com/empirical-pl/</a>.</p><p>I hope you might find this open response insightful or helpful. I welcome your thoughts or response!</p><h3>Hi,</h3><p>I spent a while reading through <a href="https://danluu.com/empirical-pl/">the article you sent</a>. The author wrote this piece in response to “strong statements” regarding the absolute superiority of typed languages. The body of the article simply reviews each example used as “evidence” for this claim, disputing each for various reasons.</p><p>The article makes the point that there is insufficient scientific evidence for static-typed languages vs dynamically-typed. Accepting this at its face, the conclusion is that one cannot be certain either way. The best position to inhabit is one of unknowing indifference: “Neither is better than the other.” This is perfectly in line with my position — absolute statements about the superiority of static or dynamic languages are unjustifiable.</p><h4>A false dichotomy</h4><p>Like any other software engineering tool, types have a potential to add value for our code and the people who develop/maintain it. Claims that “types are inferior to tests” and “any time spent writing types should be spent on more tests” creates a false dichotomy between two tools that are better used and considered in concert with each other. Both have the capability to make our code easier to understand, develop, and maintain. Knowing how/when to leverage both of these tools (and others) in order to maximize these effects, given a specific project and team, is one job of a good software engineer.</p><h4>High stakes in errors</h4><p>While it might not be possible to achieve scientific consensus on static vs dynamic languages, I feel that doesn’t prevent one from recognizing the value typed JavaScript (especially TypeScript) has brought to JavaScript app development. I have been writing JavaScript for over many years now, building large apps in large departments and teams. It is perfectly possible to create very large JavaScript applications.</p><p>However, it’s also exceptionally challenging to catch all errors (especially from more junior colleagues) before they hit production. Historically that’s been mostly survivable — nothing more than an error in a console somewhere. In the world of React Native or server-side JavaScript, however, an error means your app or server crashes! Preventing this from happening should be the #1 goal of a software engineer and accomplishing it takes expertise and the skillful utilization of every tool the engineer’s disposal, including both tests and types.</p><h4>TypeScript has made open source better</h4><p>Looking forward, I will never write another JavaScript app without leveraging or benefitting from TypeScript.</p><p>Firstly I will massively benefit from the god-send that are type definitions for all of my dependencies. This simple, zero cost thing objectively makes my application better and my developers more productive, whether I choose to add types to my own JavaScript code or not.</p><p>There are no additional costs to my project, but the upsides include better tooling and preventing whole classes of errors (that are difficult or impossible to catch by writing tests, unless you plan to never mock your dependencies). While the author or community may have had to pay the price for writing and maintaining those types, the whole world benefits a million times over for them having done so.</p><p>I cannot tell you how much time I’ve wasted over my career paging through documentation (if it exists at all), figuring out a function’s arguments and return values, and catching usage errors at runtime. Eliminating this effort entirely (or at the very least dramatically reducing it) is a real gift TypeScript has brought — and I for one will always choose to take advantage of that.</p><p>I intend to provide types to consumers of my JavaScript code, so that they can similarly benefit. Whether this consumer is in the open source community, on my team, or the poor soul debugging my code two years from now — having types can go a long way to understanding, using, and changing large opaque JavaScript codebases.</p><h4>A more balanced position</h4><p>I hope you will consider taking a new position: one that recognizes the real benefits typed JavaScript has brought to apps, teams, and the entire community, especially in early error detection, developer productivity, and tooling. Tests are a hammer and types a screw driver — not every problem is a nail nor is every problem a screw — you need to have both tools in your belt. As a software engineer, one needs to know the strengths and weaknesses of every tool at his/her disposal including when/how to use each in different projects/teams.</p><p>I hope you will carefully consider the benefits (and costs) choosing typed JavaScript could bring to your future projects.</p><p>Adam</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71e6c88b344b" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/open-response-to-tests-types-71e6c88b344b">Open response to “Tests &gt; Types”</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The zenith of React’s functional paradigms — Part 2: The worst parts of React]]></title>
            <link>https://itnext.io/the-zenith-of-reacts-functional-paradigms-part-2-the-worst-parts-of-react-6011b85ba6a1?source=rss-583b3a685d22------2</link>
            <guid isPermaLink="false">https://medium.com/p/6011b85ba6a1</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Adam Terlson]]></dc:creator>
            <pubDate>Sun, 16 Jun 2019 21:23:51 GMT</pubDate>
            <atom:updated>2019-06-17T20:03:16.070Z</atom:updated>
            <content:encoded><![CDATA[<h3>The zenith of React’s functional paradigms — Part 2: The worst parts of React</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qWovDWCK3_pik8bF" /><figcaption>Photo by <a href="https://unsplash.com/@benjaminrobyn?utm_source=medium&amp;utm_medium=referral">Benjaminrobyn Jespersen</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The two main building blocks of a functional React codebase — stateless functional components and higher order components — both have serious flaws.</p><h3>The limits of Stateless Functional Components</h3><p>I have <a href="https://medium.com/@adamterlson/functional-react-series-part-1-get-your-app-outta-my-component-92656ae13e25">published my love of SFCs</a> before. However, there were a couple reasons I couldn’t leverage them as much as I would have liked.</p><p>In React Native, the need for performance optimization isn’t a question of if, but when—eliminating unnecessary re-renders is “React Optimization 101”.</p><p>The benchmarks don’t lie: <a href="https://moduscreate.com/blog/react_component_rendering_performance/">SFCs were</a> <a href="https://itnext.io/react-component-class-vs-stateless-component-e3797c7d23ab">not the</a> <a href="https://medium.com/groww-engineering/stateless-component-vs-pure-component-d2af88a1200b">fastest option</a>. The user of especially a React Native app could possibly suffer <em>real perceptible</em> performance differences simply because the engineer chose to leverage a function instead of a class.</p><p>This is not how the world should work!</p><p>Engineers had no choice: use PureComponent (or wrap every component with an HOC, which would in turn itself use PureComponent).</p><h3>HOC component composition sucks</h3><p>HOCs are a solid choice to add functionality to your React components. Need to access state, transform props, access context, dispatch an action, or anything else you can imagine, HOCs can be how these behaviors are described (see the popularity of libraries like <a href="https://github.com/acdlite/recompose">recompose</a>).</p><p>However, taken too far, what you’re left with at the end can be a bit of a mess:</p><pre>const FinalComponent = compose(<br>    connect(...)<br>    mapProps(...),<br>    dispatchOnMount(...),<br>    defaultProps(...),<br>    ...20 HOCs later...,<br>    pure,<br>)(IncompleteComponent)</pre><p>Beyond simply being a PITA to trace/debug, achieving behavioral definition via component composition has some serious flaws that aren’t so in-your-face.</p><h4>Problem 1: Prop &amp; render marshaling</h4><p>Because props must literally flow from one component to the next, it’s the responsibility of each HOC to make sure they make it through, unmodified and uninterrupted.</p><pre>compose(<br>  withState,<br>  myCustomHOC, // Must pass all state changes through, uninterrupted<br>)(MyComponent)</pre><p>Beyond simply being a new class of error no one wants in their life, it also means it is practically<em> impossible to apply a shouldComponentUpdate in an HOC</em> — after all, preventing the HOC from re-rendering will prevent components downstream from receiving prop changes from upstream.</p><h4>Problem 2: All-or-nothing type safety on props</h4><p>In a perfect world, when writing a render method with JSX, the type system will ensure that all prop requirements of the component you’re using will be satisfied (and hopefully have working intellisense).</p><pre>const MyComponent = compose(<br>    someHOCA, // Requires prop &quot;propA&quot;<br>    someHOCB, // Requires prop &quot;propB&quot;<br>)((props: { propC: string }) =&gt; (...))</pre><pre><br>&lt;MyComponent propA={10} propB={false} /&gt; // Error - PropC is missing</pre><p>However, in order to achieve this with HOC component composition, the type system must be able to fully understand every HOC and what effect it has, if any, on props.</p><pre>const MyComponent = compose(<br>    someHOCA, // Requires prop &quot;propA&quot;<br>    someHOCB, // Requires prop &quot;propB&quot;<br>    propMap(props =&gt; ({ ...props, propC: &quot;Yes!&quot; }), // Add propC<br>)((props: { propC: string }) =&gt; (...))</pre><pre><br>&lt;MyComponent propA={10} propB={false} /&gt; // No error (hopefully)!</pre><p>This complexity (see: overhead) creates a lot of problems when trying to create a React project with good type coverage, and good (see: functional) style.</p><p>When it comes to types, it’s all or nothing. Life or death. Kill or be kil — you get the point.</p><p>If you missed it, go <a href="https://medium.com/@adamterlson/react-hooks-memo-the-zenith-of-reacts-functional-paradigms-8067dc258afb">check out part 1</a> for more on the history of React’s functional paradigms.</p><h3>Part 3: Soon</h3><p>I will discuss how these problems have been solved, and what I see as the idiomatic way forward for the functional react codebase.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6011b85ba6a1" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/the-zenith-of-reacts-functional-paradigms-part-2-the-worst-parts-of-react-6011b85ba6a1">The zenith of React’s functional paradigms — Part 2: The worst parts of React</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The zenith of React’s functional paradigms]]></title>
            <link>https://itnext.io/react-hooks-memo-the-zenith-of-reacts-functional-paradigms-8067dc258afb?source=rss-583b3a685d22------2</link>
            <guid isPermaLink="false">https://medium.com/p/8067dc258afb</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Adam Terlson]]></dc:creator>
            <pubDate>Tue, 28 May 2019 16:11:48 GMT</pubDate>
            <atom:updated>2019-06-19T13:34:36.201Z</atom:updated>
            <content:encoded><![CDATA[<h3>The zenith of React’s functional paradigms—Part 1: A Revolution in frontend</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VSg6icj9MEFuQmrj" /><figcaption>Photo by <a href="https://unsplash.com/@paulamayphotography?utm_source=medium&amp;utm_medium=referral">Paula May</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>It’s been a tough journey as an engineer using React, and as a lover of JavaScript functions. One of React’s greatest blessings, is also its curse.</p><p>Looking back, the competitive advantage of React over the likes of Angular and the <a href="https://codecondo.com/15-javascript-template-engines/">many many frontend templating</a> languages/libraries (remember those?) it competed against at the time, was that React’s render could be defined using only JavaScript functions, no need for fancy text.</p><p>This simple value, that JavaScript functions &gt; strings, laid the ground work for React’s long-term relationship (BFFL) with the functional programming community. Now the frontend engineer could build their frontend application using only functions, including its render!</p><p>Well, almost.</p><h3>The Revolution of Stateless Functional Components</h3><p>A major step forward was the introduction of stateless functional components in version 0.14, released in 2015 (2 years after initial release). It seemed to once again emphasize the way React was different from the competition.</p><p>It now became possible to define your application’s UI using a plain JavaScript function.</p><pre>const MyUI = () =&gt; &lt;em&gt;Revolutionary&lt;/em&gt;</pre><p><em>The plain JavaScript function: a revolution in web front end development.</em></p><p>One got the sense, however, of being placed with a devil on each shoulder. One tells you that classes are how we do things here; classes are necessary; they’re proper; they’re, well, classy. The other tells you to rip off all your clothes and bathe in the beautiful simplicity of functions.</p><p>Which is actually the better choice for a large scale React application was unclear. After all, one could seemingly use createClass or proper JavaScript classes for every component without any regret. One could thrive without ever writing a single stateless functional component and <em>never know of React’s inner functional nature! DAMN THOSE ATHEISTS!</em></p><p>The opposite however, to survive without classes and lifecycle, was not possible. (Attempts were made—lives were lost)</p><p>Until now.</p><h3>Part 2: The Worst Parts of React</h3><p>The practical challenges of building a large React app in a functional programming style.</p><p><a href="https://medium.com/@adamterlson/the-zenith-of-reacts-functional-paradigms-part-2-the-worst-parts-of-react-6011b85ba6a1?postPublishedType=initial">Read Part 2</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8067dc258afb" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/react-hooks-memo-the-zenith-of-reacts-functional-paradigms-8067dc258afb">The zenith of React’s functional paradigms</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Redux Saga to Mobile-First: “Don’t worry — I’ve got this.”]]></title>
            <link>https://medium.com/@adamterlson/redux-saga-to-mobile-first-dont-worry-i-ve-got-this-439279ec0e73?source=rss-583b3a685d22------2</link>
            <guid isPermaLink="false">https://medium.com/p/439279ec0e73</guid>
            <category><![CDATA[redux-saga]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[pwa]]></category>
            <dc:creator><![CDATA[Adam Terlson]]></dc:creator>
            <pubDate>Sun, 28 Oct 2018 18:12:17 GMT</pubDate>
            <atom:updated>2018-10-29T20:22:14.383Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Legendary Watcher — A Redux Saga of the mobile world</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*Od_nhEbV8wHTP_GX5tyVog.png" /></figure><p>What follows is not a technical manual for Redux Saga — it will not teach you sage wisdom like the true meaning of the word “Saga” or the difference between yield* and yield all.</p><p>Instead, it’s my way of looking at Saga in applications: not just as a tool, but a broader concept — a way of life. In doing so, I hope to make the value of Redux Saga clearer, and perhaps easier to understand.</p><p>If you’ve looked away from Redux Saga out of fear, guilt, anger, or pain… It’s time to face that challenge head on. Your life may soon depend on it.</p><p>Not to be dramatic or anything.</p><h3>Redux Saga to Mobile-First Apps: “Don’t worry — I’ve got this.”</h3><p>If you are using Redux and building mobile-first applications, whether a PWA or react-native, Redux Saga is a must-have, despite its (I believe avoidable) reputation of being hard to learn.</p><p>Redux Saga is more than an evolutionary step along the <em>callbacks — promises — async await — observables </em>chain, it’s a side effect management system.</p><p>The mobile-first world is full of side effects: user taps, push notifications, API calls, the android back button, and device connectivity to name a few.</p><p>Having a single tool to address all of them in a clear and consistent way is a must. Further, it must be written 100% independently from what is being currently displayed to the user.</p><p>This approach introduces a separation of handling long-running, asynchronous-heavy tasks from your presentation code, an important step in making any application maintainable (as exemplified by the success of MVC and classic multi-tier architecture).</p><h3>The Legendary Watcher</h3><p>Beginning to handle your application side effects with Saga begins by simply understanding its most basic pattern: a long-running function called The Watcher.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dcf039877c963afc473a6536373dd8a8/href">https://medium.com/media/dcf039877c963afc473a6536373dd8a8/href</a></iframe><blockquote>With the help of `take` this function will pause execution until an action with a type of ‘REQUEST’ is dispatched to Redux. There is also no need to prematurely use `takeEvery`, and instead we rely on the more fundamental and powerful API to describe the behavior.</blockquote><p>This watcher pattern, whether handling an API call, a button press, or a push notification, can be used to clearly and expressively describe any logic of your application with a single synchronous, pure function. The Watcher is the core.</p><blockquote>Consider having one action and watcher per side-effect source. For example, start with one ‘REQUEST’ type rather than ‘REQUEST_HEROES’ and ‘REQUEST_MONSTERS’ types, and take a configurable payload instead. No reason why multiple action creators cannot create an action of the same `type`, e.g. `requestHeroes()` and `requestMonsters()` both make ‘REQUEST’.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e2c9f666836b72603dddae3e4d28b618/href">https://medium.com/media/e2c9f666836b72603dddae3e4d28b618/href</a></iframe><blockquote>We add the saga helper `call` (simply always use it to execute any function), and `put`, which will dispatch the provided action to the redux store or other saga watchers.</blockquote><p>The Watcher is a complete, independent process and can be thought of to run concurrently, like threads in other systems. “Threads” in JavaScript!</p><p>For example, if `REQUEST` can only be handled when the app is online, we can model that by using `fork`.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c518335b91695070d8a7978530c2d32/href">https://medium.com/media/1c518335b91695070d8a7978530c2d32/href</a></iframe><blockquote>The helper `race` is blocking, and cancels `watcher` when ‘OFFLINE’ action is dispatched. The function will wait until `ONLINE` then resume the watcher.</blockquote><p>Saga code is very easy to build upon. It’s easy to describe, by adding length to our watcher, what should happen when an action occurs, but we can also control the context in which the work is to be done.</p><p>For example, where does `OFFLINE` and `ONLINE` come from?</p><h3>Dealing with Native APIs</h3><p>It’s possible to introduce any API to Redux. Some APIs provide a promise, which can be simply `call`ed directly, but many expose events. Such is the case with network status. In this situation, a channel can be used and paired with a watcher.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/97981224e7c25436e83e2928129452f5/href">https://medium.com/media/97981224e7c25436e83e2928129452f5/href</a></iframe><p>A watcher again is added to consume data from the channel and provide a chance for any other part of the Redux/Saga system to respond to the connectivity change.</p><h3>Sagas, a Friend for the Ages</h3><p>Redux Saga can be used to handle all side effects in your application. It’s syntax and advanced helpers are seen to be a burden to understand and learn, but can also be largely ignored by instead focusing on a few powerful api methods and simple, repeating patterns.</p><p>Give it a try if you haven’t already! You’ll be surprised how far you can get with just a few saga helpers and the Watcher pattern.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=439279ec0e73" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Functional React — Get your App outta my Component]]></title>
            <link>https://medium.com/@adamterlson/functional-react-series-part-1-get-your-app-outta-my-component-92656ae13e25?source=rss-583b3a685d22------2</link>
            <guid isPermaLink="false">https://medium.com/p/92656ae13e25</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[jsx]]></category>
            <category><![CDATA[mvc]]></category>
            <dc:creator><![CDATA[Adam Terlson]]></dc:creator>
            <pubDate>Tue, 02 Aug 2016 10:28:40 GMT</pubDate>
            <atom:updated>2017-01-13T10:12:13.415Z</atom:updated>
            <content:encoded><![CDATA[<p>Alternative titles I should have used to get more readers:</p><p><em>“5 simple code hacks for component reuse the backend devs don’t want you to know about!”</em></p><p><em>“This article proves you’ve been reacting wrong your entire life!”</em></p><p><em>“Using children is a GOOD thing? First you’ll be shocked, then you’ll be inspired!”</em></p><h3>Introduction to Functional React Series</h3><p>When I started writing React apps, I approached components as if they were “<a href="https://www.google.com/search?q=It%E2%80%99s+just+the+V+in+MVC">just the V in MVC!</a>” Seriously, we’ve all heard it.</p><p>I have found this to be an inferior way of thinking about and building React applications. It makes people treat React as a drop-in replacement for something like a Backbone or Angular 1.x View. In other words, people treat it like a glorified template system with partials and don’t harness the power of its functional paradigms.</p><p>Unfortunately, I find many people continue to operate under this line of thinking, and blog posts and guide articles about “Best Practices” subtly lend their support by, in but one example, using HTML controls and CSS in every presentational component they ever show.</p><blockquote>This series is about a functional way to write and conceptualize React applications.</blockquote><p>In this series-of-indeterminate-length, I will articulate what I have come to find to be a superior approach to building React applications — treating them as<strong> <em>functions, not templates</em>.</strong></p><p>I will describe how to:</p><ul><li>Separate the application you’re building and the platform its on from the components you write (Hey, that’s this one! Read on!).</li><li>Inject state into your application, and what a “container” aka “connected” aka “smart” component really is.</li><li>Implement more complex features by leveraging Higher Order Components and a compose function — it’s awesome.</li><li>Make your <em>application UI</em> understandable by looking at a single file, not dozens.</li><li>Make your codebase flat without sacrificing grokability.</li></ul><p>It’s not ambitious or anything.</p><p>This series could be useful for people of any React experience. The lessons will focus on creating a more expressive, maintainable, and reusable codebase than one would get by treating React like it’s the “V” in “MVC”.</p><h3>Part 1: Get your App outta my Component</h3><p>Imagine you’re building the new MyAwesomeCalculator app. The functions that are required to make the MyAwesomeCalculator work (add(), subtract(), clearInput(), submit(), etc) describe what the calculator does, but they aren’t coupled to it. For example, some other app that needs to add() could reuse that function, even if it’s not to build another calculator app.</p><p>So I say, the usefulness of the components you write should be similarly powerful and reusable beyond the application you’re building.</p><h4>A New Approach: Your app as the Product</h4><p>In its purest form, React is described as being “functional,” and stateless components are even defined by merely the “function” keyword (or arrow function).</p><p>Think of your app’s UI, features, routing, <em>everything </em>as the <strong>product</strong> of invoking these functions with some arguments. Your application isn’t what invokes the functions, your app is what gets returned! Those same functions could be invoked with different arguments in a different order and the result could be a totally different app.</p><blockquote>Your application isn’t what invokes the functions, your app is what gets returned!</blockquote><p>Just like the MyAwesomeCalculator’s functional capabilities are <em>described by </em>and not <em>coupled to </em>add(), subtract(), etc, its UI should be similarly descriptive, yet decoupled.</p><p>To demonstrate, I will introduce you to the Real Life Story(tm) of a project I built using React, and the utter failure I had trying to reuse two simple components because they were written like Views.</p><p>Then I’ll refactor them step-by-step.</p><h3>The App: “Event Management”</h3><p>I made (with React Native &amp; Redux) a ticketing/event management application. You know the type, show a list of events you manage, pull up a list of people who are attending, check them in with QR code ticket scanning, etc. It’s the sort of app people running events would want to use, not the people attending them.</p><p>There are things called “Events” where “Users” can sign up to attend. When they do so they become “Guests” and are on the list to be checked in at the door.</p><h4>The Components I want to Reuse</h4><p>One screen of the app shows information related to someone attending an event (a “Guest”). I made this by creating a component called “GuestDetails” and routed to it using the Navigator component provided by Facebook.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*lCw2-lmD_NpHdlNLZ_F4zw.png" /><figcaption>Top half of the GuestDetailsScreen. In blue, the GuestHeader component. The circle within is the GuestProfilePhoto.</figcaption></figure><h4>Code of GuestHeader and GuestProfilePhoto</h4><p>As I was filling out my GuestDetails component, at some point I realized that my code was getting a bit long. It was time to split some stuff out and make some More Awesome React Components!</p><pre>// Note: These components are a case study in what NOT to do.</pre><pre>// Some things have been simplified for code clarity and I&#39;ve put<br>// two components in the same block here for brevity.</pre><pre><strong>import</strong> React from ‘react’;<br><strong>import</strong> { View, Text, Image } from ‘react-native’;<br><strong>import</strong> { GuestShape } from ‘./entityTypes’; // Validation for Guests</pre><pre>// GuestProfilePhoto.js</pre><pre><strong>function</strong> GuestProfilePhoto({ guest }) {<br>  <strong>return</strong> (<br>    &lt;Image source={guest.userImage} style={...} /&gt; // Rounded Img<br>  );<br>}</pre><pre>GuestProfilePhoto.propTypes = {<br>  guest: GuestShape.isRequired<br>};</pre><pre>// GuestHeader.js</pre><pre><strong>function</strong> GuestHeader({ guest }) {<br>  <strong>return</strong> (<br>    &lt;View&gt;<br>      &lt;View style={{ flex:1, ... }}&gt; // Centered container<br>        &lt;GuestProfilePhoto guest={guest} /&gt;<br>      &lt;/View&gt;<br>      &lt;Text style={{ fontSize: 20 }}&gt;{guest.fullName}&lt;/Text&gt;<br>      &lt;Text style={{ fontSize: 10 }}&gt;{guest.countryOfOrigin}&lt;/Text&gt;<br>    &lt;/View&gt;<br>  );<br>}</pre><pre>GuestHeader.propTypes = {<br>  guest: GuestShape.isRequired<br>};</pre><p>Look! I’ve got reuse in mind already! I needed to use the same PropTypes for GuestHeader and GuestProfilePhoto without repeating the validation, so I stored the PropType shape validation for `guest` centrally and imported it from any component that took the `guest` as props.</p><p>I’m sure that’ll work out well….</p><h3>Let’s Play “Reuse the GuestHeader”</h3><p><em>Update 8/3: Though the original version remains intact below, based on </em><a href="https://mobile.twitter.com/dan_abramov/status/760869974093291520"><em>feedback I’ve received</em></a><em> I wish to clarify for the reader that “rules” in articles such as this are fickle things, and should not be considered strictly. I use the word here to mean something more like “shit that’s worked for me.” Onward!</em></p><p>To enumerate all the ways I’m an idiot and GuestHeader, GuestProfilePhoto and all components like it suck, let’s try to reuse them.</p><h4>The Naming is Wrong</h4><p>What if I wanted a similar looking header on the screen for users that <em>aren’t </em>attending an event? They’re not Guests anymore, they’re just Users at this point. Okay, so how about something more generic like “UserHeader” and “UserProfilePhoto”?</p><p>But, what if I want to reuse these components for displaying event information?</p><blockquote>Rule #1: Do not name your components after the part of state they connect to.</blockquote><blockquote>Rule #2: Do not name your components for the role they play in <em>YOUR</em> application.</blockquote><p>The moment a component is named for a particular use case, well then that’s the only use case it can be used for! In order to be reusable, presentational components must be named as if they can be connected to any piece of state and display any information.</p><p>So how about…</p><pre>// Rename GuestHeader to:<br><strong>function</strong> ScreenHeaderWithImage({ guest }) { ... }</pre><pre>// Rename GuestProfilePhoto to:<br><strong>function</strong> CircularImage({ guest }) { ... }</pre><p>Ship it! Oh, wait.</p><h4>The Props Are Wrong</h4><p>Our component is no longer named in such a way as to couple it to a particular screen’s usage, but those props sure are. My components can only work if I pass a prop called “guest” and that’s hardly reusable.</p><p>Further, looking at the cases where `guest.<em>something</em>` exists in the ScreenHeaderWithImage component, `guest` must have at least the following shape:</p><pre>// To satisfy ScreenHeaderWithImage, Guest&#39;s shape must include:<br>{ <br>  fullName: &#39;&#39;,<br>  countryOfOrigin: &#39;&#39;<br>}</pre><p>But there’s more.</p><pre>...<br>&lt;CircularImage guest={guest} /&gt;<br>...</pre><p>The entire Guest object is passed to a child component for displaying the Guest’s photo. Now the GuestHeader must be passed whatever props this thing needs <strong>in the appropriate shape </strong>or this child will break!</p><p>So, looking into that component I found that it needs a single property called `userImage` on the `guest` object. Adding that to our required props we need:</p><pre>// To satisfy GuestHeader and children, Guest&#39;s shape must include:<br>{ <br>  fullName: &#39;&#39;,<br>  countryOfOrigin: &#39;&#39;,<br>  userImage: &#39;&#39;<br>}</pre><p>What a maintenance headache! If the shape of this were to change, it breaks two different components, and it’s totally unclear from the outside what props are even used or how!</p><blockquote>Rule #3: A component should be given <strong>ONLY </strong>the props it requires. This structure should* be <strong>flat.</strong></blockquote><p><em>* One exception is when your individual parts of data are meaningless by themselves (e.g. tuples, e.g. an XY coordinate).</em></p><p>So, we could break up the props then and pass each individually:</p><pre><strong>function</strong> ScreenHeaderWithImage({ <br>  fullName, <br>  countryOfOrigin, <br>  userImage <br>}) { ... }</pre><p>This is undoubtedly a step in the right direction. But we can do better. What if I don’t want to display a userImage, but instead an image of my favorite cat (Jasper)?</p><blockquote>Rule #4: Props should not be named according to the application state that gets passed in. Instead, they should be named according to their usage within the component itself.</blockquote><p>This is just like any function you write, but is sometimes overlooked on React components. In the end, the prop is in reality <em>any</em> string that’s <em>used</em> as the source for an image, and so should be named accordingly. With that rule in mind, we get:</p><pre><strong>function</strong> ScreenHeaderWithImage({ <br>    primaryHeadline, <br>    secondaryHeadline, <br>    imageSourceUrl<br>}) { ... }</pre><h4>The PropType Validation is Wrong</h4><p>Let’s look back at the original validations being used:</p><pre>// GuestShape was imported in the previous component code snippet, <br>// but is shown inline here for stupidity demonstration purposes.</pre><pre><strong>const</strong> GuestShape = PropTypes.shape({<br>  id: PropTypes.number,<br>  fullName: PropTypes.string,<br>  isPremium: PropTypes.bool,<br>  userImage: PropTypes.string,<br>  countryOfOrigin: PropTypes.string,<br>  countryCodeOfOrigin: PropTypes.string,<br>  gender: PropTypes.string<br>});</pre><pre>GuestHeader.propTypes = {<br>  guest: GuestShape.isRequired<br>};</pre><pre>GuestProfilePhoto.propTypes = {<br>  guest: GuestShape.isRequired<br>};</pre><p><em>Nothing is `required` in GuestShape!</em></p><p>I was trying to reuse the same validation shape across multiple components, and different components needed different parts of it, so nothing could be required!</p><p><strong>By attempting to reuse PropType validation on application-specific state used as props, my state shape could change, break my app, and I wouldn’t even get so much as a warning!</strong></p><p>Now that we’ve changed up our component’s prop structure though, we can easily fix this critical point of failure:</p><pre>// Rest easy, friend.  I got ya.</pre><pre>ScreenHeaderWithImage.propTypes = {<br>  imageSourceUrl: React.PropTypes.string.isRequired,<br>  primaryHeadline: React.PropTypes.string.isRequired,<br>  secondaryHeadline: React.PropTypes.string // Optional<br>}</pre><p>Glad that’s gone….</p><h4>The Component Coupling is Wrong</h4><p>We still have one problem, and it’s a subtle one that by itself warrants its own article. It’s that the ScreenHeaderWithImage component is coupled to the CircularImage component. What if I want a SquareImage? Or no image at all?</p><p>One solution would be to pass in a prop or twenty for this:</p><pre><strong>function</strong> ScreenHeaderWithImage({ <br>    primaryHeadline, <br>    secondaryHeadline, <br>    imageSourceUrl,<br>    hasImage<br>}) {<br>  <strong>if</strong> (hasImage) { ... }<br>  <strong>else</strong> { ... }<br>  ...<br>}</pre><p>… but this is not sustainable and is still limiting. Instead, React gives us a far more powerful tool to handle the situation where a component wishes to not care about what child component(s) are used.</p><p>Composition!</p><blockquote>Rule #5: Composition is superior to import statements at the top and is the primary mechanism which allows your component to focus on doing ONE thing. Use it wherever, and whenever you can.</blockquote><p>By composing, a parent can become decoupled from its children and this allows for its own usage and function to become more granular and clear.</p><p>Wherever you are taking in some props and merely passing them unmodified to a child component, that’s also a good indication of a spot to use composition instead.</p><pre><strong>function</strong> ScreenHeader({ <br>  primaryHeader, <br>  secondaryHeader, <br>  children <br>}) {<br>  <strong>return</strong> (<br>    &lt;View&gt;<br>      &lt;View style={{ flex:1, ... }}&gt; // Centered container<br>        {children}<br>      &lt;/View&gt;<br>      &lt;Text style={{ fontSize: 20 }}&gt;{primaryHeader}&lt;/Text&gt;<br>      &lt;Text style={{ fontSize: 10}}&gt;{secondaryHeader}&lt;/Text&gt;<br>    &lt;/View&gt;<br>  );<br>}</pre><p>The ScreenHeader component is now the epitome of reusable!!!</p><p><em>Assuming you’re using React Native….</em></p><h4>The Platform Coupling is Wrong(ish)</h4><p>Let’s go crazy. What if I want to display this on the web? I can’t use this component because it’s using React Native components (View &amp; Text) as well as styling that doesn’t exist outside of React Native….</p><p>The good news is that React is just the tool for the job.</p><pre>// Replace the &quot;View&quot; with a generic container component<strong><br>import</strong> Container from &#39;./Container&#39;;</pre><pre>// Replace the &quot;Text&quot; with more semantic components<br><strong>import</strong> PrimaryHeadline from &#39;./PrimaryHeadline&#39;;<br><strong>import</strong> SecondaryHeadline from &#39;./SecondaryHeadline&#39;;</pre><pre><strong>function</strong> ScreenHeader({ <br>  primaryHeader, <br>  secondaryHeader, <br>  children <br>}) {<br>  <strong>return</strong> (<br>    &lt;Container&gt;<br>      &lt;Container centered&gt;<br>        {children}<br>      &lt;/Container&gt;<br>      &lt;PrimaryHeadline&gt;{primaryHeader}&lt;/PrimaryHeadline&gt;<br>      &lt;SecondaryHeadline&gt;{secondaryHeader}&lt;/SecondaryHeadline&gt;<br>    &lt;/Container&gt;<br>  );<br>}</pre><p>The bad news is that the problem is just pushed forward. The new components look something like this:</p><pre>// Container.js -- Depends on React Native :(</pre><pre><strong>import</strong> { View } from &#39;react-native&#39;;</pre><pre><strong>const</strong> center = {         <br>    flex:1,<br>    flexDirection:&#39;row&#39;,<br>    alignItems:&#39;center&#39;,<br>    justifyContent:&#39;center&#39;<br>};</pre><pre><strong>function</strong> Container({ centered }) {<br>    <strong>let</strong> style = {};</pre><pre>    <strong>if</strong> (centered) {<br>        Object.assign(style, center);<br>    }</pre><pre>    <strong>return</strong> (<br>        &lt;View style={style} /&gt;<br>    );<br>}</pre><pre>------</pre><pre>// Text.js -- Depends on React Native :(</pre><pre><strong>import</strong> Text from &#39;ReactNative&#39;;<br><strong>function</strong> RNTextWrapper({ size }) {<br>   <strong>return</strong> &lt;Text style={{size}} /&gt;;<br>}</pre><pre>------</pre><pre>// PrimaryHeadline.js -- Semantic titles, requires only Text above</pre><pre><strong>import</strong> Text from &#39;./Text&#39;;<br><strong>function</strong> PrimaryHeadline({ children }) {<br>    <strong>return</strong> &lt;Text size={20}&gt;{children}&lt;/Text&gt;;<br>}</pre><pre>------</pre><pre>// SecondaryHeadline.js</pre><pre><strong>import</strong> Text from &#39;./Text&#39;;<br><strong>function</strong> SecondaryHeadline({ children }) {<br>    <strong>return</strong> &lt;Text size={10}&gt;{children}&lt;/Text&gt;;<br>}</pre><p>But, the good news is that all you need to do now is rewrite these TWO components (Container and Text) to support multiple platforms!</p><p><strong>In theory</strong> <strong>:)</strong></p><h3>TL;DR All the guidelines in one place</h3><p>The idea: Presentational React components should not know about your company, its product, or the platform it’s built for. None of them exist.</p><p><strong>#1: </strong>Do not name your components after the part of state they connect to.</p><p><strong>#2:</strong> Do not name your components for the role they play in YOUR application.</p><p><strong>#3: </strong>A component should be given ONLY the props it requires. This structure should be flat.</p><p><strong>#4:</strong> Props should not be named according to the application state that gets passed in. Instead, they should be named according to their usage within the component itself.</p><p><strong>#5:</strong> Composition is superior to import statements at the top and is the primary mechanism which allows your component to focus on doing ONE thing. Use it wherever, and whenever you can.</p><p>Here are some common ways presentational components “know” about a product:</p><ul><li>By using names for a particular part of the application’s state (e.g. EventStats)</li><li>By using names based on the role the component plays in the application (e.g. RegistrationConfirmation)</li></ul><p>And some common ways presentational components “know” about a platform:</p><ul><li>By styling via CSS or RN style definitions rather than with components and semantic props (e.g. assigning props which dictate presentation is fine, just do `color={”success”}` rather than `color={‘#00cc66’}`)</li><li>By using controls provided by React or React Native (e.g. div, button, View, Text, etc)</li><li>By doing anything that depends on a browser or native app context (e.g. urls, accessing window, checking screen width, etc)</li></ul><p>I will expand much further on this topic, talk about state, and many more tricks the backend devs don’t want you to know (!) in future parts of this series, so ❤ for updates.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92656ae13e25" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>