<?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 Benjamin Cripps on Medium]]></title>
        <description><![CDATA[Stories by Benjamin Cripps on Medium]]></description>
        <link>https://medium.com/@itsBenCripps?source=rss-3bb125a453a3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lMWWdvKWJN19G2o7EGDUVg.png</url>
            <title>Stories by Benjamin Cripps on Medium</title>
            <link>https://medium.com/@itsBenCripps?source=rss-3bb125a453a3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 14:03:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@itsBenCripps/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[Speed Matters, But It Isn’t Everything]]></title>
            <link>https://medium.com/indeed-engineering/speed-matters-but-it-isnt-everything-879b4203fd9f?source=rss-3bb125a453a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/879b4203fd9f</guid>
            <category><![CDATA[engineering]]></category>
            <dc:creator><![CDATA[Benjamin Cripps]]></dc:creator>
            <pubDate>Thu, 03 Feb 2022 16:24:20 GMT</pubDate>
            <atom:updated>2022-02-03T16:24:20.427Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Iaaarx75wNRLf_Xq.jpg" /><figcaption><em>Photo by </em><a href="https://unsplash.com/@jon_chng"><strong><em>Jonathan Chng</em></strong></a><em> on </em><a href="https://unsplash.com/s/photos/collaboration?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"><strong><em>Unsplash</em></strong></a></figcaption></figure><p>Over the last few years at Indeed, we noticed our public-facing web applications were loading more slowly. We tested numerous ways to improve performance. Some were very successful, others were not.</p><p>We improved loading speeds by 40% but we also learned that speed is not always the most important factor for user experience.</p><h3>Performance metrics</h3><p>We measured loading speed using two key metrics:</p><ul><li><a href="https://developer.mozilla.org/en-US/docs/Glossary/First_contentful_paint"><strong>FirstContentfulPaint</strong></a> — when the user sees the first content of the page</li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigationTiming/domContentLoadedEventEnd"><strong>DomContentLoadedEventEnd</strong></a> — when the page becomes interactive, <a href="https://html.spec.whatwg.org/multipage/parsing.html#the-end"><strong>as measured by the moment where all critical CSS and JavaScript have been parsed and executed</strong></a></li></ul><p>We chose a weighted average instead of a single metric. This provided a more accurate measure of perceived load time, and helped us answer two critical questions:</p><ul><li>How long did the user wait before the page seemed responsive?</li><li>How long did the user wait before they could interact with the page?</li></ul><p>Though these metrics came with tradeoffs, we decided to use them instead of Google Web Vitals because they gave the broadest coverage across our user base. After deciding on these metrics, we had simple, observable, and reportable data from hundreds of applications and across a variety of web browsers.</p><h3>Successful methods for improving speed</h3><p>While we tried many strategies, the following efforts provided the biggest increases in performance.</p><h3>Flushing &lt;Head/&gt; early</h3><p>Browsers generally use the most resources during page load when they are downloading and parsing static resources such as JS, CSS, and HTML files. To reduce this cost, we can send static content early, so the browser can begin to download and parse files even before those files are required. This eliminates much of the render-blocking time these resources introduce.</p><p>By flushing the HTML head early on multiple applications, we saw load time improvements of 5–10%.</p><p>This implementation comes with a few trade-offs, however, since flushing the HTML document in multiple chunks can result in confusing error modes. Once we’ve flushed the first part of the response, we’re no longer able to change parts of the response, such as status code or cookies. Even if an error occurs somewhere before the last part of the response, we can’t change these headers. We’ve implemented some common libraries that help with these complications.</p><h3>Reducing files on the critical path</h3><p>Apart from the total number of bytes, one of the most important aspects for page load time is the number of total resources — especially render-blocking resources — required on the critical path for rendering. In general, the more blocking files you request, the slower the page. For example, a 100kB page served with 5 files will be significantly faster than a 100kB page served with 10 files.</p><p>In an A/B test, we reduced the number of render-blocking files from 30 to 12, a 60% reduction. The total amount of bytes shipped during page load was roughly identical. This test provided a 2+ second improvement for <strong>domContentLoadedEventEnd</strong> at the 95th percentile for our desktop and mobile search pages, as well as significant improvements in <a href="https://web.dev/lcp/"><strong>largestContentfulPaint</strong></a>.</p><p>To dive into this further, we explored the cost of a single extra CSS file. We ran a test on one of our highest trafficked pages to reduce the number of CSS files by 1. Page load times improved by a statistically significant amount, about 15ms at the 95th percentile.</p><h3>Improving the runtime cost of CSS-in-JS</h3><p>As more of our applications started using our newest component library, built on top of the <a href="https://emotion.sh/docs/introduction"><strong>Emotion library</strong></a>, we noticed 40% slower page loads.</p><p>The Emotion library supports CSS-in-JS, a growing industry trend. We determined that rendering CSS-in-JS components added extra bytes to our JavaScript bundles. The runtime cost of this new rendering strategy — along with the added bytes — caused this slowdown. We built a webpack plugin that precompiled many of our most commonly used components, reducing their render costs and helped address the problem.</p><p>This strategy resulted in a massive improvement, decreasing the slowdown from 40% to about 5% in aggregate, at the 95 percentiles. However, the CSS-in-JS approach still incurred more runtime cost than more traditional rendering approaches.</p><h3>Factors outside our control</h3><p>Along with testing improvements, we analyzed the types of users, locales, and devices that had an impact on page speeds.</p><h3>Device type and operating system</h3><p>For Android devices, which are generally lower powered than their iOS counterparts, we saw 63% slower timings for <strong>firstContentfulPaint</strong>, and 107% slower timings for <strong>domContentLoadedEventEnd</strong>.</p><p>Windows users saw 26% slower timings for <strong>domContentLoadedEventEnd</strong> compared to their iOS counterparts. These results were somewhat expected, since Windows devices tend to be older.</p><p>This data provided important takeaways:</p><ul><li>The performance impact of features and additional code is non-linear: newer, robust devices can incur 100kB more code without an impact to performance, while older devices see a much bigger slowdown as a result.</li><li>Testing applications using real user metrics (RUM) is critical to understanding performance, since performance varies so widely based on device and the operating system’s capabilities.</li></ul><h3>Connection type and network latency</h3><p>We used the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Network_Information_API"><strong>Network Information API</strong></a> to collect information about various connection types. The API is not supported in all browsers, making this data incomplete, however, it did allow us to make notable observations:</p><ul><li>4G connection types were 4 times faster than 3G, 10 times faster than 2G, and 20 times faster than connections that were less than 2G. Put another way, network latency accounts for a huge percent of our total latency.</li><li>For browsers that report connection type information, 4G connection types make up 95% of total traffic. Including all browser types drops this number closer to 50%.</li></ul><p>Networks vary greatly by country, and for some countries it takes over 20 seconds to load a page. By excluding expensive features such as big images or videos in certain regions, we deliver simpler, snappier experiences on slower networks.</p><p>This is by far the simplest way to improve performance, but it comes at the cost of complexity.</p><h3>Results of speed and other factors</h3><p>The impact of performance on the web varies. Companies such as Amazon have reported that <a href="https://www.fastcompany.com/1825005/how-one-second-could-cost-amazon-16-billion-sales"><strong>slowdowns of just 1 second could result in $1.6 billion in lost sales</strong></a>. However, other case studies have reported a more muddled understanding of the impact of performance.</p><p>Over the course of our testing, we saw some increases in engagement based on performance improvements. But we’re not so sure they’re strongly correlated to performance improvements alone.</p><h3>Reliability vs speed</h3><p>Our current understanding of these increases in engagement is that they are based on increased reliability rather than an improvement in loading speed.</p><p>In tests where we moved our static assets to a content delivery network (CDN), we saw engagement improvements, but we also saw indications of greater reliability and availability. In tests that improved performance <strong>but not reliability</strong>, we did <strong>not</strong> see strong improvements in engagement.</p><h3>The impact of single, big improvements</h3><p>In tests where we improved performance by a second or more (without improving reliability), we saw no significant changes in our Key Performance Indicators.</p><p>Our data suggests that for non-commerce applications, small to medium changes in performance do not meaningfully improve engagement.</p><h3>Engagement vs performance</h3><p>Our observations reminded us not to equate performance with engagement when analyzing our metrics. One stark example of this point was the different performance metrics observed for mobile iOS users versus mobile Android users.</p><p>While Android users had nearly 2 times slower rendering, there was no observable drop in engagement when compared to iOS users.</p><h3>So when does speed matter?</h3><p>After a year of testing strategies to improve speed, we found some that are worth the effort to improve performance. While these improvements were measurable, they were not significant enough to drive changes to key performance indicators.</p><p>The bigger lesson is that while a certain level of speed is required, other factors matter too. The user’s device and connection play a large role in the overall experience. The silver lining is that knowing we cannot fully control all these factors, we can be open to architectural strategies not specifically designed for speed. Making minor trade-offs in speed for improvements in other areas can result in an overall better user experience.</p><p><em>Cross-posted on the </em><a href="https://engineering.indeedblog.com/blog/2022/01/speed-matters/"><em>Indeed Engineering Blog</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=879b4203fd9f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/indeed-engineering/speed-matters-but-it-isnt-everything-879b4203fd9f">Speed Matters, But It Isn’t Everything</a> was originally published in <a href="https://medium.com/indeed-engineering">Indeed Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reviving a legacy TypeScript Application]]></title>
            <link>https://medium.com/@itsBenCripps/reviving-a-legacy-typescript-application-15dd9cff56ca?source=rss-3bb125a453a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/15dd9cff56ca</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Benjamin Cripps]]></dc:creator>
            <pubDate>Sat, 22 Dec 2018 13:08:57 GMT</pubDate>
            <atom:updated>2018-12-22T13:12:29.379Z</atom:updated>
            <content:encoded><![CDATA[<h3>Reviving a Legacy TypeScript Application</h3><p>Recently I came across a project written in TypeScript that was established in 2014. That’s was only <a href="https://en.wikipedia.org/wiki/TypeScript">2 years after the creation</a> of TypeScript, and much, much before it’s increase in popularity. And as such, the project was starting to show it’s age.</p><h3>Some Background</h3><p>When the project began, much of the amazing open source tooling and configurations for TypeScript didn’t exist yet. That includes a much improved <a href="https://github.com/Microsoft/TypeScript">TypeScript core</a>, and a much more robust set of rules for <a href="https://github.com/palantir/tslint">TSLint</a>, that includes <a href="https://github.com/palantir/tslint/blob/master/src/configs/recommended.ts">tslint-recommended</a> and <a href="https://github.com/prettier/tslint-config-prettier">tslint-prettier-config</a>.</p><p>After upgrading the TypeScript dependency and adding these new configurations, I found that this (pretty large application) had over 50k lint/compiler errors.</p><p>Pretty daunting. But hey, that’s half the fun.</p><h3>TypeScript made some things easy</h3><p>About 95% of these errors were due to prettier’s opinionated approach to spacing, and line lengths — these errors fixed themselves by running our lint command with the --fix argument.</p><p>But that still left about about 2500 actual errors.</p><p>Some of these issues were actually hard to find/reproduce bugs. And we were able to fix these in a fairly straightforward way.</p><p>However, for many (I’d say about ~250), we took the safest approach, by adding some <a href="https://palantir.github.io/tslint/usage/rule-flags/">tslint-ignore</a> comments where it made sense.</p><h3>So what didn’t TypeScript make easy?</h3><p>I was extremely surprised to find that TSLint didn’t auto-fix uses of var to the preferred const and let keywords. More than that, I was downright annoyed.</p><p>TSLint would throw errors during lint, but the --fix command provided no help. And we didn’t want to go and add ignore comments, or fix hundreds of variable declaration.</p><p>So instead, we used a little bash to change all of our var declarations to let:</p><pre>find -name &quot;*.ts&quot;  -exec sed -ie &quot;s/var/let/&quot; {} \;</pre><p>Which transforms this code:</p><pre><br>var thing = 1;<br>var thing2 = 2;<br>thing2 += thing1;</pre><p>into</p><pre>let thing = 1;<br>let thing2 = 2<br>thing2 += thing1;</pre><p>and from there we could simply tun tslint -- --fix which turned our code into:</p><pre>const thing = 1;<br>let thing2 = 2<br>thing2 += thing1;</pre><p>and voila, all 50k errors in our application have been fixed.</p><h3>Conclusion</h3><p>For me, the power in doing this kind of work is less about fixing old issues, especially in applications that serve a business need. The true power in making these fixes is in enabling better code to be written in the future. Sure, we did fix some bugs, but more importantly, we’re also going to stop letting future bugs be written.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15dd9cff56ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Code Coverage with Webpack v2]]></title>
            <link>https://medium.com/@itsBenCripps/implementing-code-coverage-with-webpack-v2-63fa527fc723?source=rss-3bb125a453a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/63fa527fc723</guid>
            <category><![CDATA[webpack-2]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Benjamin Cripps]]></dc:creator>
            <pubDate>Wed, 01 Mar 2017 18:08:37 GMT</pubDate>
            <atom:updated>2017-03-01T18:10:19.458Z</atom:updated>
            <content:encoded><![CDATA[<p>Upgrading to webpack v2 should be simple. And for the most part it is; the team has done an amazing job simplifying the exposed API and (more impressively) documenting the changes and providing upgrade paths.</p><p>It took me about 25 minutes to get one of my projects (which I’ve <a href="https://medium.com/@itsBenCripps/open-sourcing-a-redux-component-bb82f260ff62#.evnov65ui">written</a> about in the past) from webpack v1 =&gt; webpack2. I wasn’t doing a whole lot, using a handful of open-source loaders, with a different configuration for testing (using Karma, and karma-babel-prepocessor) to transpile my ES6/React into testable code (in the JSDOM environment). All in all, a pretty standard webpack setup for a React project.</p><h4>So if it’s so simple, then why even write this blog post?</h4><p>Two words: Code Coverage.</p><p>The merits of code coverage, whether it’s a flawed metric (it is), whether it tells you about the health of the system (it does), will not be discussed here, since that’s a much larger topic. The point of this article is simply about the implementation.</p><p>Like I said, for me, everything just worked after the upgrade — and I was able to remove a lot of the boilerplate required for v1, which v2 was able to abstract away or perform by default (requires, better globbing for excludes, etc). But code coverage didn’t work. At all. And not only did it not work — but it broke my entire testing workflow.</p><p>At the bottom I will link to the entire changeset that shows upgrading from v1 =&gt; v2, but I’ll mention the biggest gotcha.</p><p>With webpack v1, I was using two preloaders in order to implement code-coverage.<strong> </strong>A loader to transpile my code from React/ES6 to testable ES5, and a loader to actually instrument the code:</p><pre>{<br>     test: /<strong>\.</strong>js$|<strong>\.</strong>jsx$/,<br>     loader: &#39;babel-loader&#39;,<br>     exclude: /node_modules/<br>},<br>{<br>     test: /<strong>\.</strong>js$|<strong>\.</strong>jsx$/,<br>     loader: &#39;isparta&#39;,<br>     exclude: /node_modules|test/<br>}</pre><p>However, since v2 now handles babel loader by default, and the mechanism that instruments the code is Bablyon (and not Babel) which <strong>does not</strong> use the .babelrc, when the code was getting to isparta-loader, it hadn’t transpiled my fancy React or ES6 — and of course, it broke immediately.</p><p>Here’s the new loader:</p><pre>{<br>    test: /<strong>\.</strong>js$|<strong>\.</strong>jsx$/,<br>    enforce: &#39;post&#39;,<br>    loader: &#39;istanbul-instrumenter-loader&#39;,<br>    exclude: /node_modules|test/,<br>    query: {<br>        esModules: true<br>    }<br>}</pre><p>So now we only have a single loader, which gets executed at the <strong>post</strong> stage rather than pre, and at this point the code has already been transpiled, so we don’t need to worry about whether the code is in the correct format. Our loaders (and the corresponding presets) have taken care of that for us already.</p><p>And Voila! code coverage with webpack v2. I will link two changesets here, the first shows the upgrade path from v1 =&gt; v2, without removing a lot of the cruft not required by v2. The second changeset removes the no longer required code.</p><p><a href="https://github.com/bencripps/react-redux-grid/commit/261f21814b780098712cfb913cba1122b4e5768c">Changeset 1</a>: Upgrade to Webpack 2</p><p><a href="https://github.com/bencripps/react-redux-grid/commit/5055622ebcbdedcc86f4614e7adda195b6c8eca7">Changset 2</a>: Cleanup after Upgrade</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63fa527fc723" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Async JavaScript, there and back again]]></title>
            <link>https://medium.com/@itsBenCripps/async-javascript-there-and-back-again-744b1fb90432?source=rss-3bb125a453a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/744b1fb90432</guid>
            <category><![CDATA[async]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[es7]]></category>
            <dc:creator><![CDATA[Benjamin Cripps]]></dc:creator>
            <pubDate>Sat, 04 Feb 2017 15:48:05 GMT</pubDate>
            <atom:updated>2017-02-04T21:33:48.867Z</atom:updated>
            <content:encoded><![CDATA[<p>Async programming in JavaScript has always been a fairly advanced, convoluted, and somewhat annoying concept. I think every JS programmer gets asked more than one async question in an interview. Here’s one of my favorites:</p><pre>var Api = function() {<br>    var ret = [];</pre><pre>    for (var i = 0; i &lt; 3; i++) {<br>        ret.push(function() {<br>            return i * 2;<br>        });<br>    }</pre><pre>    return ret;<br>};</pre><pre>var data = Api();</pre><pre>console.log(data[0]())<br>console.log(data[1]())<br>console.log(data[2]())</pre><p>I’m sure you’ve seen this one before, but the question is “what does this program log”? How do we fix the bug? Why does the bug happen? For bonus points, does ES6 give us any tools that helps us with this scenario, and so on.</p><p>The point of this post isn’t to answer this question, but you’re welcome to spend on time on it, maybe post an awesome answer in the comments. The point of this post is to talk about Async JavaScript — where we used to be, where we are now, and where we’re going. (Hint, we’re making progress!)</p><h4>Ugh, Remember this?</h4><pre>function getData(userId) {<br>    <br>    var cb = function(data) {<br>        if (!data) {<br>            // apart from getUser and getOrders needing their own<br>            // errorHandling, all our other callbacks need<br>            // them as well :(<br>            throw new Error(&#39;There was an error retrieving data!&#39;);<br>        };<br>        document.querySelector(&#39;#user&#39;)<br>            .innerHTML = JSON.stringify(data);<br>    };</pre><pre>    // aync request user<br>    getUser(<br>        userId, <br>        // async callback to be fired<br>        // when getUser finishes<br>        // binding another callback to be fired<br>        // when getOrders finishes<br>        getOrders.bind(this, cb)<br>    );<br>};</pre><p>In this scenario, we need to make an API call to get a user, and upon the return of that call, we need to request some orders that the user made. Upon the return of that call, we can finally append that info to the DOM. This is just gross code, but it used to be all we had.</p><h4>And then we got Promises</h4><p>Promises are an inversion of our normal workflow, but they make for much more tenable code. Take a look at this:</p><pre>const getData = userId =&gt; getUser(userId)<br>    .catch(handleError)<br>    .then(getOrders)<br>    .catch(handleError)<br>    .then(data =&gt; document.querySelector(&#39;#user&#39;)<br>        .innerHTML = JSON.stringify(data));</pre><p>Ok sure, I’m using ES6, so it looks prettier, but it’s also simpler. And simpler is always better. I think the most important thing here, is that we’re able to provide a default error handling utility to each API call, without having to gross up the code inside those methods. It’s also easier to quickly scan through — it’s very obvious that getOrders is chained to getUser, and it’s much more obvious what is happening with the final data.</p><h4>Oh man, now we get Await</h4><p>I think of all the ES6 and ES7 features, await is going to have the most effect on producing quality code.</p><pre>async function getData(userId) {<br>    try {<br>        const user = await getUser(userId);<br>        const order = await getOrders(user);</pre><pre>        document.querySelector(&#39;#user&#39;)<br>            .innerHTML = JSON.stringify(data);<br>    }</pre><pre>    catch (e) {<br>        throw new Error(&#39;There was an error retrieving data!&#39;);<br>    }<br>};</pre><p>Let’s look at what is awesome about this:</p><ol><li>We’re able to wrap both of our API calls in a single try/catch and we can handle our error dynamically, based on the e argument passed to our catch clause.</li><li>We don’t need to jump through hoops to chain/structure our code any differently than we would if this code was entirely synchronous.</li><li>It’s super obvious what is happening.</li></ol><h4>Conclusion</h4><p>None of this is ground breaking news — the await syntax has been complete for a while now, and it’s stage-4 which means it’s nearly set in stone. But it’s nice to see where we used to be, how promises revolutionized the work flow, and how await is going to make dealing with async processes even simpler.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=744b1fb90432" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Open Sourcing a Redux Component]]></title>
            <link>https://medium.com/hackernoon/open-sourcing-a-redux-component-bb82f260ff62?source=rss-3bb125a453a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb82f260ff62</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[open-sourc]]></category>
            <dc:creator><![CDATA[Benjamin Cripps]]></dc:creator>
            <pubDate>Fri, 03 Feb 2017 15:42:43 GMT</pubDate>
            <atom:updated>2019-04-30T08:25:07.021Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the story all about how I built (with the incalculable help of <a href="https://github.com/taco">taco</a>) a React/Redux Grid Component, appropriately (and boringly named) <a href="https://github.com/bencripps/react-redux-grid">React-Redux-Grid</a>.</p><p>This is about how we started building a thing, how it changed along the way, the things we messed up, the things we learned, the things we’d do differently, and the things we’re going to do going forward.</p><h3>Starting to Build a Thing</h3><p>At the time, I was working for an organization that was revamping their UI stack from Ext JS to a more modern platform based on <a href="https://facebook.github.io/react/">React</a>. Without going into too much back story, our existing app was a monolith with dozens of views, hundreds of rich UI components, and a bunch of spaghetti holding together our concept of <em>state management </em>(more on this later). In short, we had a bunch to rebuild (exciting!), refactor (hard!), and reimagine. One of the big obstacles for us was that we needed a robust grid component since much of our application was built around displaying and interacting with tabular data. Although we did our research, we couldn’t find an extensible enough grid that suited our UI and data needs. I will also admit that we had a penchant for creating things early on, since our previous applications heavily involved extending EXT’s components rather than building our own, and we were feeling bitten by that mantra.</p><p>Very early, we knew we were going to commit to React. The community was behind it, it fit our functional tastes, and the API was clean and expressive. We got a little lucky in choosing <a href="https://github.com/reactjs/react-redux">Redux</a>, though we toyed with <a href="https://facebook.github.io/flux/docs/overview.html">Flux</a> and <a href="https://optimizely.github.io/nuclear-js/">Nuclear</a>, finally choosing Redux because the single-store metaphor made sense to us.</p><p>I didn’t stop to think why our UI Components needed to be <strong>connected</strong> via Redux. Now, of course, I fully understand the convenience of having component state accessible via the `store`. It’s pretty cumbersome having to jump through hoops, retrieving React state from the component instance. But honestly I don’t think I thought about that at the time. I think I just wanted a Redux Component because it was an interesting problem.</p><p>Anyways, here’s the short list of high-level requirements we came up with prior to building:</p><p>* Handle large data sets<br>* Open-ended event model, where DOM interactions can correspond to certain callbacks<br>* Each row needs to be able to trigger dynamic menus and actions<br>* Support a flat list or tree structure<br>* Resizable/Orderable columns<br>* Custom rendering models for cells<br>* Editable rows, validation, persistence<br>* Tested. Fully tested.<br>* Fast. Real fast.<br>* Extensible/Modular Style</p><p>Although we ran into a bunch of problems immediately, I’m only going to touch on the most interesting ones:</p><h4>The `DOM` Problem</h4><p>Now we all know that React renders things as a tree — which is great. Well it’s usually great. Take a look at this grid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5QYkar2fYHaw0tGLNAZvHg.png" /></figure><p>What do we notice? We have a header and some rows. Simple right? Well, yes, and no. The problem here is that we have a scrollable container with a bunch of rows, and a disparate header that should be in sync with all of these rows.</p><p>What’s the big deal you say? Well let’s look at the hypothetical DOM structure this presents:</p><pre>&lt;table&gt;<br>    &lt;thead&gt; …headers &lt;/thead&gt;<br>    &lt;div style=”overflow-y:auto”&gt;<br>        &lt;tbody&gt;<br>            &lt;tr&gt;&lt;/tr&gt;<br>            …more rows<br>        &lt;/tbody&gt;<br>    &lt;/div&gt;<br>&lt;/table&gt;</pre><p>I’m sure you’ve guessed by now that this just isn’t going to work with React. If we tried this DOM, and believe me, we did, we’d get the following error:</p><pre>Warning: validateDOMNesting(…): &lt;tbody&gt; cannot appear as a child of &lt;div&gt;</pre><p>Which makes sense, since yeah, that’s pretty gross HTML. I’d also like to note that making a <strong>&lt;tbody&gt;</strong> scroll nicely seems nearly impossible. But since we needed to be able to resize columns, and we didn’t want to have to rely on <a href="https://hackernoon.com/tagged/javascript">JavaScript</a> to keep our headers and our cells aligned (because of overall expense), we needed a new solution. We came upon the following solution because although React makes creating invalid <a href="https://hackernoon.com/tagged/html">HTML</a> impossible, it makes rendering HTML super cheap and efficient:</p><pre>&lt;div&gt;&lt;!--overall component container -&gt;<br>    &lt;table&gt;&lt;!--table for just our visible headers--&gt;<br>       &lt;thead&gt;<br>           …headers<br>       &lt;/thead&gt;<br>    &lt;/table&gt;<br>    &lt;div style=”overflow-y:auto”&gt;<br>        &lt;table&gt;<br>            &lt;thead style=”visbility:hidden;”&gt;<br>                …copy of above headers<br>            &lt;/thead&gt; &lt;!-- invisible headers --&gt;<br>            &lt;tbody&gt;<br>                &lt;tr&gt;&lt;/tr&gt;<br>                …more rows<br>            &lt;/tbody&gt;<br>       &lt;/table&gt;<br>    &lt;/div&gt;<br>&lt;/div&gt;</pre><p>We end up with a lot more DOM here, but we get something pretty powerful as well. Although we have two HTML copies of our Header component, they are actually the exact same React components (so no extra code required) — being driven by the same slice of Redux state (no extra state required). This was incredibly helpful. When one of the visible headers is resized, although it doesn’t update the corresponding cells automatically, it <strong>does</strong> update the Redux store with a new width prop. That width is also driving the invisible header’s width, which then triggers the browser to resize the corresponding &lt;td&gt;’s in the scrollable container.</p><p>And <em>Viola</em>, we have two disparate tables communicating via Redux state. We are <strong>dispatching</strong> an action when header actions occur, but we don’t need to keep track of cell width (which would be painful and expensive).</p><p>This was one of the first “ah-ha” moments for me, working with React and Redux. I kept running into problems I had solved before with things like jQuery or Angular that React made a little more difficult (like the invalid DOM problem). But when it came to core view-centric problems like having to efficiently update the DOM, or sensibly managing state, React simply made those afterthoughts. I really didn’t need to care at all, so I didn’t.</p><h4>The ‘Making it Fast’ Problem</h4><p>React is fast, but there’s always ways to optimize for speed. Although we went through a <strong>shouldComponentUpdate</strong> phase, where we nailed down each component so they only redrew when needed, I’m going to talk about how we optimized <strong>connect</strong> for our problem space.</p><p><a href="https://github.com/reactjs/react-redux/blob/master/docs/api.md)">Connect</a> is a decorator exposed by Redux that essentially hooks a component up to the Redux store so that it can read out of the state atom. There is a bunch more to it (that’s incredibly important for performance optimization) but for our purposes, that’s probably enough. The only other thing I’ll say is that we incur a bit more overhead since all connected components are “listening” for state changes, and must run through <strong>mapStateToProps</strong> anytime the store gets updated.</p><p>We can see from our final DOM structure, that we’re going to have a bunch of components. The problem that grid poses more than other UI components is scale. For example, in our app we often had instances of thousands of records on a single page, each record with dozens of properties we wanted to display. That’s<strong> a lot</strong> of DOM, but it’s also a lot of event listeners, and JavaScript objects in memory, etc.</p><p>We started out by connecting everything — hey, everything needed to read from the store! That meant our header, the scroll-container, the footer, every row, and yes, every single cell. It worked — kind of. Sure it rendered, but interactions were too sluggish and redraws weren’t 60 fps crisp. We needed to do something different.</p><p>That’s all the details on the problem for now, since I’m going to discuss this in the “Things We Messed Up” section. But I will just say that our final solution (which maybe we should rethink) is to only have a single connected component — the grid container. That way we only run through <strong>mapStateToProps</strong> once, and we pass our props all the way down the chain, letting <strong>shouldComponentUpdate</strong> handle the rest. This resulted is some untenable code at times, but a lightning-quick reconciliation/render cycle.</p><h4>The ‘What do we Export’ Problem</h4><p>That brings us to a non-technical problem. At the time of inception, building a “Redux-Component” was a relatively new idea. There were React components that exposed a single export — the component itself. Sometimes they bundle CSS dynamically, and sometimes you needed to import a stylesheet manually.</p><p>But Redux is a little different because it brings the added dependencies of a store, reducers, and actions. Did these need to be exported? We didn’t know. We guessed they did, but to be honest, we weren’t sure until we started using the component ourselves.</p><p>We ended up exporting everything — including the demo store. We wanted the grid to run on its own so people could `git clone` and see how it worked themselves, kind of like a UI REPL. But we didn’t want to impose any pattern beyond the simplest usage. It’s via that thinking that we came up the following exports:</p><pre>export const modules = {<br>    Actions,<br>    Grid,<br>    Reducers,<br>    applyGridConfig,<br>    Store<br>};</pre><p>It’s obvious to us now that the actions were a necessary export since they turned out to be the public API for the grid — how you communicate information to the component via <strong>dispatch</strong>. We also exposed a number of reducers, each responsible for their own slice of the grid state (i.e. data, columns, editor, pagination). In my mind, this made dealing with grid as heavy or as light as the importing developer wanted. But now I sort of feel like that’s one of the more annoying parts of the component. It makes for cleaner code inside grid, but for a more annoying API. Oh well, so it goes.</p><p>We also exported a couple utilities, and this is the area where I think we will spend our near term efforts — building some more utilities that make working with grid a little simpler.</p><p>We decided to include CSS dynamically at runtime, but to make it optional. By default the CSS will be appended to the document, but can ignored by setting a property via the <strong>applyGridConfig</strong> function. One of the simple joys for me, in this new brave React world, is that components can truly be self-sufficient and sandboxed — it always irked me that I needed to include CSS via &lt;link rel&gt; tags with jQuery components.</p><h3>Things We Messed Up</h3><p>This section could and should be the longest part of this story. But it’s not going to be, probably out of self-preservation.</p><h4>Using ImmutableJS the Wrong Way</h4><p>This brings us back to <strong>connect</strong>. Since we were worried about the connection cost, we simply reduced the number of decorated components we were authoring — to 1. This got us nearly the whole way, except that we saw big lags in performance when the data-set got large (1000+), and that didn’t sit well with us.</p><p>We starting diagnosing the problem using <a href="https://facebook.github.io/react/docs/perf.html">React Perf</a> tools and saw that we were spending almost no time in wasted cycles. Here’s the readout from React-Perf:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c5KFGMTSiUPCK8Zd_CrGdQ.png" /></figure><p>What, we were only wasting 1.8ms on a grid with 10,000 rows? We weren’t needlessly recalculating props for components, and we weren’t needlessly redrawing either. So what was the problem?</p><p>We opened up the browser profiler (<a href="https://developers.google.com/web/tools/chrome-devtools/rendering-tools/">Chrome’s</a> is first rate, if you’ve never used it), and we recorded a session where we performed a couple click events. We experienced the heavy lags we were consistently seeing with large data sets, so we went to profile logs to see what was going on.</p><p>Nearly<strong> 25%</strong> of the JavaScript runtime was being spent in garbage collection. And even more alarming, nearly <strong>8%</strong> of the time was spent in <a href="https://facebook.github.io/immutable-js/">ImmutableJS</a>’ <strong>toJS</strong> function? For a couple single click events?</p><p>When I think about this now, it’s so obvious that this was due to our poor implementation of <strong>mapStateToProps</strong> which involved heavy deserialization of immutable data structures to plain JavaScript objects. However, back then, I remember this blowing my hair back. I remember thinking ‘what the hell kind of memory leak required 15% of our execution memory?’. And ‘what the hell is wrong with toJS?’. Here’s a simplified version of what was going on:</p><pre>export const mapStateToProps = (state, props) =&gt; ({<br>    gridData: stateGetter(state, ‘dataSource’, props.stateKey),<br>});</pre><pre>export const stateGetter = (<br>    state, key, gridStateKey<br>) =&gt; state.getIn([key, gridStateKey]).toJS();</pre><p>For each property that we cared about, whether it was columns, or data, we were converting our immutable data (which was being stored in our reducers) to plain JavaScript objects in <strong>mapStateToProps</strong> since the innards of grid were operating on native objects instead of immutable ones (some kind of feeble attempt at separation of concerns).</p><p>We knew, even then, that <strong>toJS</strong> was going to be expensive, but what we didn’t know was that <strong>mapStateToProps</strong> runs even before <strong>shouldComponentUpdate</strong> thanks to Redux. So anytime an action fired, we recursively toJS()ed our entire state node for the grid. This explained why we saw the problem grow linearly as the data sets got larger. It also explained the crazy amount of garbage collection, since the execution of <strong>mapStateToProps</strong> didn’t even do anything with the newly created native objects — specifically when an event didn’t require a redraw, those fresh new objects were simply thrown away.</p><p>The solution was simple after we figured out where and what the problem was. We simply removed the <strong>toJS</strong> calls and made the innards of grid work with immutable data. This is where we got the biggest performance boost. Since this change, we haven’t run into any real performance snags at all. Looking back now, I think this was my most egregious error, causing me to change the way I thought about open source libraries as a whole (more on that below).</p><h4>Requiring a `store` Prop</h4><p>This has since been remedied, but up until version 5.0.0, a Redux store was one of the required props for grid. It simply wouldn’t run unless the store was explicitly provided. I chalk this one up to not analyzing the landscape as grid matured. We ended up <a href="https://github.com/bencripps/react-redux-grid/pull/82">solving</a> this very easily by simply pulling the store from <strong>context</strong>, the pattern many other popular Redux frameworks had already implemented.</p><h3>Things we Learned Along the Way</h3><p>Maybe this should be the longest section? No probably not, we messed up a lot along the way.</p><h4>Take a look around</h4><p>Although we were venturing out into unknown territory (especially myself), every time we didn’t know the solution to a problem, we were able to peruse other popular GitHub repos to see how something was accomplished, or what pattern was being employed. This is something I wish I would have done at every step of the way. A minute of research can save you weeks of refactoring.</p><h4>Open Source is a lot of work</h4><p>And it’s worth it. But open source projects don’t get awesome until you have a bunch of people all working together. I can’t tell you how exciting it is to have people you don’t know (and without provocation) collaborating on a project. Some of the most creative and sweeping changes come from having a new set of eyes on an old problem.</p><p><strong>Submit a Pull Request.</strong> If you don’t want to, or you don’t know where to start, <strong>open an Issue</strong> or ask a question.</p><h4>Testing pays dividends</h4><p>Over the course of grid’s lifetime, its undergone 3 heavy refactors. Removing connect, and modifying components to use immutable objects required nearly full rewrites of much of the source. Because we were stalwarts in the beginning about adding tests, and checking coverage, these refactors were made easier, and felt less burdensome. It was a really great feeling completing a refactor and watching your tests pass. Even better, when a couple failed for good reason, corrections were made, and we could feel confident about what we had built.</p><h4>Understand the tools you use</h4><p>I’ve always thought about libraries as black boxes. If I needed a utility/component/thing, and it’s been built before, why recreate the wheel right? Sure, you learn the API and you use the tool to solve the problem at hand. But beyond that, I generally didn’t go look inside to see how that problem is solved. And that bit me here — I had a fundamental misunderstanding of how Immutable worked, and that caused a lot of pain and refactoring. If I’ve learned anything, it’s that before choosing your tools, take a moment to see how they work, if they’re truly right for the job, and <strong>make sure</strong> you implement them correctly.</p><h3>And Now to the Future</h3><p>Here’s a list of things we’d like to accomplish in the near to long future, in no particular order:</p><p>* Implement selectors<br>* Addition of new UI plugins (row expansion, etc)<br>* Add more extensibility around filtering data<br>* More fleshed out examples for the demo site<br>* Implement drag and drop for flat data<br>* Better documentation</p><p>Please open a pull request and accomplish one of these goals! Or come up with a better idea! Or go fix some bugs, or refactor some of the gross away.</p><p>At the time of writing, grid is at v5.1.8. We’ve come a long way, but we’d like to go a lot further.</p><blockquote><a href="http://bit.ly/Hackernoon">Hacker Noon</a> is how hackers start their afternoons. We’re a part of the <a href="http://bit.ly/atAMIatAMI">@AMI</a>family. We are now <a href="http://bit.ly/hackernoonsubmission">accepting submissions</a> and happy to <a href="/service/mailto:partners@amipublications.com">discuss advertising &amp;sponsorship</a> opportunities.</blockquote><blockquote>To learn more, <a href="https://goo.gl/4ofytp">read our about page</a>, <a href="http://bit.ly/HackernoonFB">like/message us on Facebook</a>, or simply, <a href="https://goo.gl/k7XYbx">tweet/DM @HackerNoon.</a></blockquote><blockquote>If you enjoyed this story, we recommend reading our <a href="http://bit.ly/hackernoonlatestt">latest tech stories</a> and <a href="https://hackernoon.com/trending">trending tech stories</a>. Until next time, don’t take the realities of the world for granted!</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb82f260ff62" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/open-sourcing-a-redux-component-bb82f260ff62">Open Sourcing a Redux Component</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>