<?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 Yaroslav Serhieiev on Medium]]></title>
        <description><![CDATA[Stories by Yaroslav Serhieiev on Medium]]></description>
        <link>https://medium.com/@noomorph?source=rss-f7e1fbcd5bef------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*hcRsjcM7R7U2K8Jr.png</url>
            <title>Stories by Yaroslav Serhieiev on Medium</title>
            <link>https://medium.com/@noomorph?source=rss-f7e1fbcd5bef------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 10:07:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@noomorph/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[Two mistakes in React.js we keep doing over and over again]]></title>
            <link>https://medium.com/wix-engineering/two-mistakes-in-react-js-we-keep-doing-over-and-over-again-b1aea20fb3f0?source=rss-f7e1fbcd5bef------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1aea20fb3f0</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-performance]]></category>
            <dc:creator><![CDATA[Yaroslav Serhieiev]]></dc:creator>
            <pubDate>Wed, 20 Feb 2019 14:01:01 GMT</pubDate>
            <atom:updated>2019-03-04T10:46:25.117Z</atom:updated>
            <content:encoded><![CDATA[<h3>Two mistakes in React.js we keep making over and over again</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*dJQD0_U6gZvq1VCebJHSdA.png" /></figure><p>Recently I was given a privilege to spend a whole two weeks, freestyle, on hunting down performance issues in a large-scale React Native app. There were a few good starting points that the QA team had suggested — some of the screens had a disturbingly slow reaction to such simple actions as tapping on a checkbox or typing a text into an input.</p><p>As my investigation went on, a bunch of seemingly isolated cases started resembling rather a deep rabbit hole. While it all started from a struggle with inefficient practices in user-facing components, I ended up with a discovery of similar shortcomings in React Native’s codebase itself:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kno98Z-mYbkVGv5I2u9ORg.png" /><figcaption>Down the rabbit hole, towards React Native repo</figcaption></figure><p>Through this story, I want to share with you a few lessons that, in my opinion, are half-learned by many of us — the root cause of why we keep rubbing React’s fur the wrong way.</p><h3>The Curious Case of Country Selector</h3><p>I ask myself, if, in the beginning, I were to answer what can possibly go wrong with performance on the country selector screen below, could I assess how many potential points of failure I was up to discover? With all due skepticism, the reality has surpassed my wildest expectations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*qKDRcF3wWP3SCLQflJTdTQ.png" /><figcaption>Country Selector Demo</figcaption></figure><p>Basically, in this multi-selection list, we need to display all countries of the world, plus provide a “select all” checkbox and a quick search by name. At first sight, nothing special. So, what could be happening in an ordinary Redux app as you tap on a country item checkbox?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JgwfL9-2f6zCiBB5EO6nvg.png" /><figcaption>Scenario — tap on a checkbox</figcaption></figure><p>Here is a rough outline of how I’d personally expect the data flow to occur in this case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cl8PMvmDbrkttv_p6OFqaA.png" /><figcaption>My expectation for the data flow in “tap on country” scenario</figcaption></figure><p>Eight or so steps, a piece of cake for the modern hardware… but here is what I saw in reality on a very similar screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*ohebb8J0HzhOLkbxrRuuew.gif" /><figcaption>When React gets mistreated</figcaption></figure><p>Two eternities later, I even began to doubt if I ever made that tap on “South Korea” — all together, 7 seconds passed before I could see that white-on-green checkmark appearing. No doubt, something had to be done about it.</p><p>It had been a long time since my last dive into performance troubleshooting in React Native, so to refresh the memory and to make sure I wouldn’t overlook new insights or tools that had emerged meanwhile in React ecosystem, I put on replay a relevant presentation by Jean-Remi Beadouin I had a pleasure to see first-hand last November on React Day Berlin 2018.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F9sWxSQCZ4us%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D9sWxSQCZ4us&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F9sWxSQCZ4us%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d65edc24f48ed997191b0c1f35db768b/href">https://medium.com/media/d65edc24f48ed997191b0c1f35db768b/href</a></iframe><p>So far, the most important slide to me was this one, the listing of relevant tools for in-app performance troubleshooting:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RU5OJ90P7Grj8Zd3bAqa-Q.png" /></figure><p>Below is a direct link to his presentation and this particular slide:</p><p><a href="https://slides.com/jrbeaudoin/troubleshooting-a-slow-app-a-practical-guide-to-great-react-native-performance#/0/15">Troubleshooting a slow app, a practical guide to great React Native performance</a></p><p>Without hesitation, I installed <strong>why-did-you-update</strong> npm package and monkey-patched the entry point to the app:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b9d6eac363ad3f3f69619bca7b0a462f/href">https://medium.com/media/b9d6eac363ad3f3f69619bca7b0a462f/href</a></iframe><p>Pay attention at those two tweaks I did above to avoid issues with React’s <strong>YellowBox</strong>: the first — to disable it, and the second — to exclude it from <strong>why-did-you-update</strong> console logs. Otherwise, I would have run into the loop when a <strong>YellowBox</strong> would be shown to display a warning about an issue inside <strong>YellowBox </strong>— guess when the loop ends? <em>Hint: never, at least in my specific React Native app, though your mileage may vary.</em></p><h3>Mistake #1: 100 updates = 1 useful + 99 useless</h3><p>Moving on, this is what I saw in the Console tab after cleaning all logs and tapping once on that list item:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2uydqWj9zpDJqMsqoRHkjg.png" /><figcaption>why-did-you-update warnings, thousands of them!</figcaption></figure><p>You may notice that each wastefully updated component prints 2 warnings (one for state, and one for props), so I had an amused smile when I realized that here we have 3430 extra renders for one innocent tap.</p><p>The curiosity drove me to immediately try out the second recommendation on the list — Chrome debugger’s flame chart. In itself, visualizing the ongoing activity in React Native components turned out to be a dead simple task, done in four steps. Try this out if you haven’t already!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iGggGUj7sMwSrzFSDftvsw.png" /></figure><p>The picture I had discovered, once again confirmed the scale of futile activity happening behind the curtains:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w_gzvZTLXY6C8ooaajgNKQ.png" /></figure><p>So, why did that happen? I mean, only a handful of nodes were meant to be updated, and, speculatively, I can even tell which ones.</p><p>If we adhere to the immutability principle, and that is the premise behind the further reasoning, we know that instead of mutating an object or an array on a change, we should create a new instance of the latter. By that, we don’t lose its previous state irrevocably and yet ensure that strict equality check (===) returns false. To be on the safe side, I decided to supplement this paragraph with a code snippet as an illustration:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b9a11be213e56c12c9518859965859c/href">https://medium.com/media/0b9a11be213e56c12c9518859965859c/href</a></iframe><p>Keeping that in mind, let’s go over the chain of updates, we would typically expect when, for example, your reducers had already processed a tap on “Aland Islands.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*WPQo6Sf0uJbPjWmwfyHR3Q.png" /><figcaption>Component updates as we expect them to happen due to the changes in props (marked as red)</figcaption></figure><ul><li>first of all, the connected <strong>CountrySelector</strong> component should have a force update from Redux’s <strong>Connect</strong> <a href="https://reactjs.org/docs/higher-order-components.html">HOC</a> (i<a href="https://gist.github.com/gaearon/1d19088790e70ac32ea636c025ba424e">f it is not clear why, see its simplified version on Gist</a>),</li><li>the underlying stateless template-like <strong>CountrySelector</strong> should update due to the changed property <strong>countries</strong> (as an array, it is expected to have a new reference since one of the items in that array has been modified),</li><li><strong>FlatList</strong> should update because its <strong>data</strong><em> </em>prop is different (for the same reason as <strong>countries</strong>),</li><li><em>only 1 out of about 200 underlying </em><strong><em>CellRenderer</em></strong><em>-s should update (not shown on the diagram, they are </em><a href="https://github.com/facebook/react-native/blob/0.57-stable/Libraries/Lists/VirtualizedList.js"><em>private components of </em><strong><em>VirtualizedList</em></strong></a><em>, the underlying component behind </em><strong><em>FlatList</em></strong><em>) — that’s easy to explain, because the rest of </em><strong><em>CellRenderer-s </em></strong><em>should receive array elements identical by reference, as none of them has been changed except for the array item associated with “Aland Islands”,</em></li><li>the <strong>ListItem</strong> with “Aland Islands”<strong> </strong>should update due to the new value of prop <strong>checked</strong> (=true) and a new reference to its country data item (as for the latter, it is supposed to be passed into always identical <strong>onChecked</strong> callback every time you tap on the checkbox),</li><li>and the <strong>CheckBox</strong> inside that <strong>ListItem</strong> should update because its value has explicitly been changed (from <em>false</em> to <em>true</em>).</li></ul><p>In all fairness, I might have omitted a couple of props, but that’s not the point. I mean that, in total, maybe 6, maybe 10, maybe 15 components have to be updated — that, of course, depends on the nesting of components and other implementation details — but that’s not a magnitude of thousands we would expect here.</p><p>Before we continue, let’s revisit the diagram of React component lifecycle methods to understand my reasoning better. Although below is an updated version (for React 16.4 and later), the points made further are relevant to an equal extent to the older React versions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yG6wM_vNzZNflWWLX91Cgg.png" /><figcaption>Image source: <a href="https://blog.bitsrc.io/understanding-react-v16-4-new-component-lifecycle-methods-fa7b224efd7d">https://blog.bitsrc.io/understanding-react-v16-4-new-component-lifecycle-methods-fa7b224efd7d</a></figcaption></figure><p>We know that React team has been encouraging the use of pure components (where it makes sense) for quite a while, and there’s no need to prove the obvious — update operations are apt to be long enough to stop us from being careless, especially when they involve some good 20–50 nodes. Moreover, that country selector, broken performance-wise, has vividly demonstrated what is going to happen if you lose control over updates in a big hierarchy of elements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*_-O-t1TceqLqsYkok0CBdg.png" /><figcaption>A modest but a crucial part of update lifecycle</figcaption></figure><p>I can’t overstate the importance of this modest red cross in React’s update lifecycle, especially if we figuratively “zoom out,” to grasp the entire hierarchy of components on the examined screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ryrlnag50fKcc6l6JHz3UQ.png" /><figcaption>Updates the way they should be</figcaption></figure><p>Of course, my sketch cannot include the entirety of those 3000+ components in the example. With it, I want to stress how many components we can stop from entering the heavier parts of the update lifecycle, just with proper tuning of <strong>shouldComponentUpdate</strong> mechanism.</p><p>On the legend, I mark the components that undergo the full update lifecycle with a shade of red, the ones that exit early on <strong>shouldComponentUpdate </strong>— with its less saturated shade, and the ones that are entirely out of the loop — with white.</p><p>If I were to draw those updates the way they happened on that unfortunate screen, I should have repainted the whole tree just with red, and this could happen any day in an ordinary React app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mAPh7UZOnB3fooY7InZVOQ.png" /><figcaption>Grim reality — updates, updates everywhere</figcaption></figure><p>The good news is that these performance issues while being common, are still easy enough to fix. After dealing with a few problematic screens, I have identified a few places where the culprits usually dwell, so I’ll share a few insights on how we can fix such places and prevent their emergence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XPjuOUzR3-Nvi0N4mDd2xw.png" /><figcaption>A cut of Redux data flow under the examination</figcaption></figure><p>Let’s start in reverse order, from 4 to 1.</p><h4>1.4. Your subcomponent is not actually pure</h4><p>It won’t hurt to briefly revisit what a pure component is, especially since it takes a few lines in JavaScript to express the idea:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e5cb9a677a6206df2e43c22cac25854/href">https://medium.com/media/8e5cb9a677a6206df2e43c22cac25854/href</a></iframe><p>In other words, a pure component is the one that updates only when its props or state change, and, while you don’t necessarily want such limited behavior in all scenarios, it still is a typical case in a React app, and usually it’s an acceptable limitation for your average component.</p><p>Consider an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/19f673bef4b366d3d62cf8e70eb662b9/href">https://medium.com/media/19f673bef4b366d3d62cf8e70eb662b9/href</a></iframe><p>If <strong>Ownee</strong> inherits from a plain <strong>React.Component</strong> class, that means whenever its <strong>Owner</strong> decides to render, the <strong>Owner</strong> is going to render its <strong>Ownee</strong> together with all respective <strong>OwneeOfOwnee</strong>-s of the latter (albeit, they are painted differently on the diagram to emphasize that they, however, might stop updating if their <strong>shouldComponentUpdate</strong> returns false).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6PAHTsI_S_9TfsrksIf9iw.png" /></figure><p>This behavior is not inherently bad, but at times it may decrease the update performance if you have many components to render inside <strong>Ownee</strong>.</p><p>Most likely, the things above were something everyone already knew about <strong>Component</strong> and <strong>PureComponent</strong>, but here’s something that caught me completely by surprise — that is, <a href="https://medium.com/groww-engineering/stateless-component-vs-pure-component-d2af88a1200b">React’s stateless components.</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d98a28431cc5948220a58d55cedd7d1f/href">https://medium.com/media/d98a28431cc5948220a58d55cedd7d1f/href</a></iframe><p>I must confess, until a month ago, for some reason, I was convinced that a <strong>stateless component</strong>, generally speaking, behaves the same way as any <strong>PureComponent</strong> would. I mean, it is required to be a pure function, so at some point of time, I generalized that everything about a stateless component must be pure, including the behavior of <strong>shouldComponentUpdate</strong>.</p><p>However, that was a misconception, and I whistled upon my discovery that the opposite is true — a <strong>stateless component</strong> behaves exactly like a good old <strong>React.Component </strong>— whenever an owner renders, the ownee and ownees of the ownee render as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/995/1*bd4y5D_ontn9O18hwQCg-A.png" /></figure><p>So, if a flame chart shows that<strong> a heavy stateless component</strong> gets often updated<strong> on non-relevant changes</strong>, what remedies are available then?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85ac61886ba3bba14c7e0dba06082f20/href">https://medium.com/media/85ac61886ba3bba14c7e0dba06082f20/href</a></iframe><ul><li>The most straightforward choice is to refactor your stateless component to a class derived from <strong>React.PureComponent</strong> (see the diff below):</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7320d56b068245d670d793be1fe67a0f/href">https://medium.com/media/7320d56b068245d670d793be1fe67a0f/href</a></iframe><ul><li>To obtain more control over its update conditions, you can derive from a plain <strong>React.Component</strong> class and implement your custom <strong>shouldComponentUpdate</strong> method (see <a href="https://reactjs.org/docs/react-component.html#shouldcomponentupdate">the relevant docs</a>):</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba720bedd688f7a3d7c88f69a6935d36/href">https://medium.com/media/ba720bedd688f7a3d7c88f69a6935d36/href</a></iframe><ul><li>Alternatively, you can leverage the high-order <strong>React.memo</strong> component, introduced in React 16.6, and keep your stateless component the way it is, provided you wrap it with <strong>memo</strong>:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25c2462c3591ee2fe78c9c672bcfe5ff/href">https://medium.com/media/25c2462c3591ee2fe78c9c672bcfe5ff/href</a></iframe><ul><li>For an extra degree of control, you can pass a custom props equality comparer as a second argument to <strong>React.memo</strong>, as shown below:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/616fe9f6f150878f8ae54ffbb8c8c483/href">https://medium.com/media/616fe9f6f150878f8ae54ffbb8c8c483/href</a></iframe><p>It should further be noted that:</p><ol><li>The recipe is not intended to be exhaustive, as not always you can make a component pure just by changing three lines of code. Some components may need a total rewrite lest you break their logic by brutal putting <strong>PureComponent</strong> onto them, and at the end of the day, not all components need to be pure. That brings us to the second remark.</li><li>Adding <strong>PureComponent</strong>-s recklessly here and there is apt to have the opposite effect on your performance. It seems like there is an apocryphal story about Airbnb going too far with using <strong>PureComponent</strong>, to an extent when it started hurting the performance.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pApoj20LFHHn5cM-WdVEBw.png" /><figcaption><a href="https://github.com/yannickcr/eslint-plugin-react/issues/1667">https://github.com/yannickcr/eslint-plugin-react/issues/1667</a></figcaption></figure><p>So, as the adage credited to Paracelsus says,<em> “The dose makes the poison.”</em> In other words, do not optimize just for the sake of it. Every time you strive to optimize a piece of code, you need to measure various indicators before and after, to see if your changes actually improve and do not undermine the performance.</p><h4>1.3. Your render function creates new references in child props components</h4><p>Let’s call such props <em>evernew</em>. Oh, this is a wide-spread and very annoying pest in React apps. Before I make the point, let’s revisit the concept of shallow equality between objects.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5b8d7bce89bff7f9968937c46404279/href">https://medium.com/media/d5b8d7bce89bff7f9968937c46404279/href</a></iframe><p>While some minutiae may be different, it follows that if two arguments, <strong>a</strong> and <strong>b</strong>, are not identical by reference, but they both are objects with the same keys, and for all given keys the corresponding values are strictly equal between <strong>a</strong> and <strong>b</strong>, then <strong>a</strong> and <strong>b </strong>can be considered equal.</p><p>I suggest going over a few examples to make sure we are on the same page:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b81f9124160b6c25aa68cb1563ae042/href">https://medium.com/media/8b81f9124160b6c25aa68cb1563ae042/href</a></iframe><p>So, while primitive values in props are considered equal, neither <strong>objects</strong> nor <strong>arrays</strong> or <strong>functions</strong> are going to be. The more you pass anonymous objects, arrays, and functions to props of child components, the more their respective <strong>shouldComponentUpdate</strong> methods respond: “Yes, sure, let’s update!”. So the more your update tree gets “red,” as I previously illustrated on the update tree diagram, the more frustrated your users are going to be with increasing delays between taps and UI reaction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ryrlnag50fKcc6l6JHz3UQ.png" /><figcaption>Try to not “paint” all your update tree red, please!</figcaption></figure><p>However, this is not the ultimate truth. At times, a component update tree is too light to feel the consequences of deoptimization. Also, a component might be already in bad shape owing to the efforts of your predecessors — what is dead may never die, so to say — and another prop created along the way won’t really matter (except you care about keeping technical debt low 😉).</p><p>I have prepared a few katas on how to deal with this antipattern, and here is the first one:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/818cc835cd2f88d84e62cd4f677dc532/href">https://medium.com/media/818cc835cd2f88d84e62cd4f677dc532/href</a></iframe><p>As you see here, on every <strong>RegionManage</strong> render, we are luring its <strong>FlatList</strong> to join the computational party with a fresh-baked arrow function we pass to its <strong>renderItem</strong> prop. Performance penalty here increases as the more list items get involved.</p><p>The simplest way to stop tricking <strong>FlatList</strong> into rendering items (with always a quote-unquote drastically different <strong>renderItem</strong> function) is to convert <strong>RegionManage</strong> into a class and turn that arrow function into a class instance method as shown below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64c654ce16c2af00b739659e8293cb3a/href">https://medium.com/media/64c654ce16c2af00b739659e8293cb3a/href</a></iframe><p>What did we solve by that? With this change, whenever <strong>RegionManage</strong> gets an update not related to the items in that <strong>FlatList</strong>, it is going to leave it alone and concentrate on updating its more relevant siblings.</p><p>However, we have not solved the issue entirely, because on every list item render we still are passing an arrow function to <strong>onRemove</strong> property (see line 16). That means if the list gets updated, then all the items inside are going to be updated along for the ride.</p><p>Although the use of an arrow function is somewhat justified there since we need access both to <strong>this.props</strong> and to the <strong>item</strong> in the closure, it is not the end of the world yet. All we need to make it perform better is to teach the underlying <strong>TaxRegion</strong> to pass <strong>rule</strong> into the <strong>onRemove</strong> callback.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/30a2e2bdd3a8c08000e510fa5e0069c1/href">https://medium.com/media/30a2e2bdd3a8c08000e510fa5e0069c1/href</a></iframe><p>See how that immediately simplifies our code in <strong>RegionManage</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/74c9a1500d5cbaee04a0ba80dd41c0da/href">https://medium.com/media/74c9a1500d5cbaee04a0ba80dd41c0da/href</a></iframe><p>So now, the list items won’t be rendered in vain. As for the arrow function we left inside <strong>Region</strong> component (line 7 of <em>Region.diff</em>), I’d leave it as a homework for you, but in any case that can be solved by converting it to a class and adding a bound method, as I have demonstrated earlier on <strong>RegionManage</strong> component.</p><p>Before you say “Whoa! That guy tells us to give up functional programming, how dare you!”, I can reassure you there are ways to achieve the same results in functional style, although the code might end up looking more sophisticated. Here is a quick-n-dirty example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eea0b1d232f41fbed6ef150010810915/href">https://medium.com/media/eea0b1d232f41fbed6ef150010810915/href</a></iframe><p>That’s another perspective on how we can leave <strong>RegionManage</strong> stateless through extensive use of <strong>WeakMap</strong>-based memoizing. I don’t want to get us off the subject by explaining why the <strong>memoizeWeak</strong> trick works, but, to put it simply, this function in itself is similar to <strong>_.memoize</strong>, except that it can handle more than one argument correctly and it’s not expected to create memory leaks by design. As some of you might know, this class of solutions has a drawback — weak data structures cannot accept primitives as keys, so either you pass no numbers, strings, booleans, nulls, and undefined-s, or you resort to regular <strong>Map</strong> and <strong>Set</strong> for such memoizing, taking the risk of memory leaks.</p><p>I’m not ruling out other ways to keep props shallowly equal between renders. On the contrary, I leave it up to you to find your own ninja style. Moreover, the next case with a shared UI component, <strong>ListItem</strong>, bears testimony to the diversity of decisions you can make.</p><p>This particular<strong> ListItem</strong> class historically grew plenty of shaped props (complex objects), just like <strong>checkbox</strong> prop in the example below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba0ffe0414090e0d4623b08634f9bb14/href">https://medium.com/media/ba0ffe0414090e0d4623b08634f9bb14/href</a></iframe><p>As I found out in the investigation process, the dealbreaker for <strong>CountrySelector</strong> performance with <strong>ListItem</strong> was that passing each time a new object for its <strong>checkbox</strong> prop triggered a full render inside. That was one of the major causes for why <strong>CountrySelector</strong> had been so slow.</p><p>Well, if we recall how <strong>PureComponent</strong> decides whether it should update, this behavior is justified — a new <strong>checkbox</strong> object is not going to be strictly equal to a new <strong>checkbox</strong> object, no surprise. Nevertheless, I found it extremely challenging to comply with that requirement of strict equality between <strong>checkbox</strong> objects in props — I had to ensure I generated identical objects whenever <strong>value</strong> and <strong>onValueChange</strong> were equal between renders.</p><p>On my every single attempt, either I found myself installing a weak memoization library, or building complicated selectors with <a href="https://github.com/reduxjs/reselect"><strong>reselect</strong> package</a>. This way or another, it had been ending up looking so sophisticated that in the end, I gave up, as I didn’t believe I had to take such desperate measures just in order to satisfy that objectively limited mechanism of <strong>shouldComponentUpdate</strong> in <strong>PureComponent</strong>.</p><p>Thus, I changed tactics and replaced <strong>shouldComponentUpdate</strong> with my custom implementation that ditched strict equality checks for shaped properties like <strong>checkbox</strong>, <strong>button</strong>, and others in favor of shallow ones.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc6347f65f898b14d37a22cf99b94465/href">https://medium.com/media/dc6347f65f898b14d37a22cf99b94465/href</a></iframe><p>I hope that the code above conveys the idea of overriding equality checks for specific properties in a declarative way, but if not — you can examine the implementation of <strong>configureShouldComponentUpdate</strong> <a href="https://github.com/wix-incubator/configure-should-component-update/blob/v0.1.1/src/configureShouldComponentUpdate.js#L19">here on GitHub</a>.</p><p>Therefore, passing an anonymous object into <strong>checkbox</strong> prop, after I relaxed checks in <strong>shouldComponentUpdate</strong>, ceased to be a performance crime (see line 5):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba0ffe0414090e0d4623b08634f9bb14/href">https://medium.com/media/ba0ffe0414090e0d4623b08634f9bb14/href</a></iframe><p>The only crime remaining (line 7) was that we still were accessing that <strong>item</strong> from a closure inside <strong>onValueChange</strong> arrow function to pass it into <strong>onSelectRow</strong>. Have we seen that somewhere before? Of course! Scroll up if you have already forgotten.</p><p>So all we need is to ensure that <strong>ListItem</strong> passes that <strong>item</strong> to <strong>checkbox.onValueChange</strong> on its own implementation level, and that’s it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9cf7858270b1b4669b7ed5789d46cfb3/href">https://medium.com/media/9cf7858270b1b4669b7ed5789d46cfb3/href</a></iframe><p>Summing up, you have enough degrees of freedom to work around <em>evernew</em> props antipattern — at the very least, you can:</p><ol><li>Extract arrow functions out of JSX, convert them either to static named functions or to bound class methods (if you need access to <strong>this</strong> keyword).</li><li>Implement passing arguments to callback props on a child component level, so that its parent does not have to rely on closures in arrow functions. That way, you won’t need arrow functions anymore.</li><li>If you feel it is too challenging to avoid <em>evernew</em> props in a specific case, consider overriding <strong>shouldComponentUpdate </strong>— at times it is going to be a cleaner solution. Keep in mind, however, that it might be a code smell, and you ought to rewrite your component creatively (with React Context, component composition or whatever may work for you).</li></ol><p>Last but not least, there are ESLint rules you can leverage to prevent those places from happening in the first place, e.g., <a href="https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-bind.md">jsx-no-bind</a>, <a href="https://github.com/cvazac/eslint-plugin-react-perf/blob/master/docs/rules/jsx-no-new-object-as-prop.md">jsx-no-new-object-as-prop</a>, <a href="https://github.com/cvazac/eslint-plugin-react-perf/blob/master/docs/rules/jsx-no-new-array-as-prop.md">jsx-no-new-array-as-prop</a> and some others (personal thanks to <a href="https://github.com/ilyaivanov">Ilya Ivanov</a> for sharing that with me).</p><h4>Interlude: when &lt;FlatList&gt; surprised me after all the optimizations</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*GF0jL4FCvlUk_cetkjDXsQ.gif" /></figure><p>Eventually, after I had resolved most of the <strong>why-did-you-update</strong> warnings on that screen, the user experience significantly improved.</p><p>However, I had a gut feeling that not all is over because I could not eliminate those thin spikes under the <em>“ScrollView [update]” </em>bar. They appeared to be almost instantaneous, yet numerous updates of <strong>CellRenderer</strong> component used somewhere inside React Native’s <strong>VirtualizedList</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DDDwQQK-awjl04NgXxE4Fg.png" /></figure><p>After one more investigation, I concluded that this was caused by passing an item-related data into the <strong>extraData</strong> prop of the <strong>FlatList.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/727d95f6b5cdddb772cdc49b07427d53/href">https://medium.com/media/727d95f6b5cdddb772cdc49b07427d53/href</a></iframe><p>Since the set of <strong>selectedCountriesIDs</strong> was tightly coupled with individual item actions like “tap to select or deselect,” therefore, on every checkbox toggle, it had been inevitably changing. What I didn’t realize back then, was the fact that when you pass <strong>extraData</strong> to the <strong>FlatList</strong>, the <strong>FlatList</strong>, in turn, passes that <strong>extraData</strong> to every rendered list item! Hence, every list item is doomed to update since the previous <strong>extraData</strong> cannot be equal to the next one by definition, as it carries selected IDs.</p><p>So, only the fact that the underlying template in <strong>renderItem</strong> had <strong>shouldComponentUpdate</strong> properly optimized, prevented React from further rendering downwards the children.</p><p>When I redefined the data model to stop depending on <strong>extraData</strong> as a source of information about specific items like on the snippet below…</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d9f4a03b2342932d916307a7a7b577bd/href">https://medium.com/media/d9f4a03b2342932d916307a7a7b577bd/href</a></iframe><p>… eventually, I got a chance to see this picture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cIeAUwhtJoyfYc7cXi9Omw.png" /><figcaption>The holy grail — no extra spikes on the flame chart</figcaption></figure><p>You may see here that only one <strong>ListItem</strong> has updated during <strong>FlatList</strong> update lifecycle, which is a win. However, what makes the story even more interesting, is that it did not happen immediately after the rewrite!</p><p>At first, after all my effort to redesign data model, those familiar spikes under <em>“ScrollView [update]”</em> wouldn’t go away.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DDDwQQK-awjl04NgXxE4Fg.png" /><figcaption>Not so easy to make those spikes go away, as it turned out</figcaption></figure><p>When I was out of the options, realizing that I had done everything possible and impossible, I again rummaged through<strong> why-did-you-update </strong>logs and noticed unexpected warnings coming directly from React Native classes. It occurred to me to google them up, just for kicks, and wow!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kcz0qmHgW9ydwVnZMYy2CQ.png" /><figcaption>Source: <a href="https://github.com/facebook/react-native/issues/20174">https://github.com/facebook/react-native/issues/20174</a></figcaption></figure><p>What my surprise was when I saw an <a href="https://github.com/facebook/react-native/issues/20174">issue</a> on Github with a complaint on a very similar arrow function to those we examined before, forgotten in the depths of React Native.</p><p>Fortunately, we’ve been collaborating with <a href="https://github.com/christianbach">a guy</a> who made <a href="https://github.com/facebook/react-native/pull/21163">a fix for that shortcoming</a> and already have merged the fix <a href="https://github.com/wix-playground/react-native/pull/5">into our fork</a> of React Native. The official repository has <a href="https://github.com/facebook/react-native/issues/20174">that performance bug</a> until now (Feb 2019). While its implications are not catastrophic, it slows down the responsiveness of lists in React Native quite a bit, given they approach hundreds of items and more.</p><p>The message is, no one is immune to mistakes, and to this deoptimization in particular, even React Native — at times.</p><p>So, constant vigilance, ladies and gentlemen!.. and may the force of ESLint, React Profiler and why-did-you-update be with you!</p><h4>1.2. Your selector is malfunctioning</h4><p>We are not over, by the way. There are more places where you can mess up with performance in React, and Redux apps, specifically.</p><p>It is common to use <a href="https://github.com/reduxjs/reselect">selectors with Redux</a>, which can make your app more efficient in two ways: selectors save time on heavy calculations, and they automatically return identical references when a calculation is not required. No need to explain why identical references are nice to have — see section 1.2.</p><p><strong>reselect </strong>leverages a light and concise memoization technique, and all its code fits into the snippet below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f03b388fd0e33a265b0d3200c443415/href">https://medium.com/media/2f03b388fd0e33a265b0d3200c443415/href</a></iframe><p>While this example is perfectly fine:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5504266bb22bb05b3500781a0add8ad6/href">https://medium.com/media/5504266bb22bb05b3500781a0add8ad6/href</a></iframe><p>This similar one is not:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c60fc058fb5dc99db3a8c59025833913/href">https://medium.com/media/c60fc058fb5dc99db3a8c59025833913/href</a></iframe><p>I’m happy if you have already connected the dots, but if not — let’s look at the <strong>defaultMemoize</strong> implementation once more. After you finish, move on to the next paragraph.</p><p>Both selectors are singletons, so to say — consequently, every one of them has only one slot to keep information about its previous invocation. While this is not an issue for <strong>getActiveTodo</strong>, as the app state exists in a single copy, the problem with <strong>getTodoDisplayProps</strong> is that it is likely to be used for iteration over an array of todo items (and what else for? — a rhetorical question):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/116948cbc10fec5077f7463ab83f8edb/href">https://medium.com/media/116948cbc10fec5077f7463ab83f8edb/href</a></iframe><p>Since every time an argument is not strictly equal to the one from the last invocation, we are going to keep creating new object references on every <strong>getTodosForDisplay</strong> call.</p><p>Under these conditions, it gets more challenging to prevent update lifecycle reaching to a subcomponent with a repeater inside, even if a change in the current state was not related to <strong>state.todos</strong> at all. Besides, the <strong>getTodosForDisplay</strong> selector is unequivocally suboptimal, and for the sake of common sense, it would be better to write it as a plain function than to leave it as is.</p><p>However, if you wish to take your chances with using item-specific memoization on selectors level, you can try out, at the very list, the weak memoization trick I mentioned in section 1.2:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65b704d389ca9486d3ce5edacc10fd8a/href">https://medium.com/media/65b704d389ca9486d3ce5edacc10fd8a/href</a></iframe><p>Once again, I want to emphasize that weak memoization is liable to bite a hand and inadvertently adds unnecessary complexity to application code. I admit that I had to use this technique in one place, but that’s mostly because I was afraid to suggest a more massive pull request with proper component restructuring, despite that the latter would exempt me from the need to use <strong>memoizeWeak</strong>. On the other hand, the risk to break something was lower, so I suggest to consider this approach as a temporary, symptomatic treatment, but it’s up to you.</p><h4>1.1. Your reducer is more immutable than it should be</h4><p>Imagine a potential implementation of the country selector screen in Redux. If a said country reducer was to process a presumed <em>TOGGLE_COUNTRY_SELECTION</em> action, it could have done that in two visually similar, but drastically different performance-wise ways.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0ed92e5095cfd94de2fb45d81076674/href">https://medium.com/media/a0ed92e5095cfd94de2fb45d81076674/href</a></iframe><p>The issue here slightly resonates with the selectors’ example above. A better reducer would optimize creating new references for the objects that have not been factually changed (see line 8 in <em>countryReducer-good.js</em>), while a worse implementation would create new object references all the time, and that would complicate further distinction between changed and unchanged props. It is not deadly, but it is likely to confuse some of the pure components inside your hierarchy and make them update for no good reason.</p><h3>Mistake #2: 1 render creates 100 elements</h3><p>Last but not least, try to avoid long render functions that create dozens of various JSX elements. It is essential in the light of partial bulk updates over UI elements. One of the prime examples is “Select all” functionality I have on the examined screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*eJRTZb6h7__cUTGIL8IjEg.gif" /><figcaption>Scenario — tap on “Select all countries”</figcaption></figure><p>You may notice that time to select all countries approaches 1.5 seconds here — at least, that’s what I saw in iOS simulator on my laptop. So this is how the flame chart looks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BtZRdNLoWE4FMPqtJ_TCUA.png" /></figure><p>When we have a long flat render, we have to process updates (significant or not) in a big number of owned components, whether we like it or not.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85ac61886ba3bba14c7e0dba06082f20/href">https://medium.com/media/85ac61886ba3bba14c7e0dba06082f20/href</a></iframe><p><strong>Important notice: </strong>if you think that rewriting it into a <strong>PureComponent </strong>with numerous helper function calls makes it update any faster, you are very wrong! The structure stays the same, and it is still flat here:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e02d7f295e396ccc175a6363985c7ed2/href">https://medium.com/media/e02d7f295e396ccc175a6363985c7ed2/href</a></iframe><p>That is, one <strong>ExpensiveComponent </strong>has six children and many-many ownees (concealed inside <strong>renderComponent11</strong>,…, <strong>renderComponent62</strong>). In terms of my analogy with red-pink-white update tree, any update here would look like the whole tree painted red:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LzSP09M_yRMayK7UUne6Yg.png" /></figure><p>You can probably see what suggestion is coming next —why don’t we repaint more nodes into white and pink?</p><p>To achieve that, we should arrange children as logically independent groups. For our case, a simple geographical grouping (e.g., left part, middle part, right part) may work out well enough. If we contain every group inside a pure component that knows better when to update, then on certain massive updates we can skip 50–70% of render work, because, often enough, only one part inside every list items needs to be updated, like a list item checkbox in the case with <em>Select All </em>scenario.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3ryHyshN0OaPzVNCb-5_YQ.png" /></figure><p>This small refactor decreased update time from 1.5s to 0.5s, which is a quick win and a low-hanging fruit. So, if you find yourselves in a similar situation, this trick might prove useful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rosm4MrUguZatbARew6ygQ.png" /></figure><h3>Summary</h3><p>If UI slowly responds to simple actions like tapping on a checkbox in your React Native app, it’s a good time to arm yourself with <strong>why-did-you-update </strong>and <strong>Chrome debugger’s flame chart</strong>. Usually, the treatment is local in terms of codebase, recuperation is fast, and the result is noticeable and pleasing.</p><p>Avoid passing <em>evernew</em> props to children components. If you feel like you can enable ESLint performance rules on a permanent basis in your project, go for it — a linter never gets tired while you as a human definitely do.</p><p>The reason for the title — <em>“Two mistakes in React.js we keep doing over and over again” — </em>is that these days the issue is as valid as it was a few years ago. I hope I’ve managed to link together in one place many of the insights scattered over articles of past years and also share the first-hand experience from a different angle, using React Native app as an example.</p><p>With knowledge comes responsibility — make sure your fellows are aware of coding habits in React that compromise performance and don’t repeat the same mistakes twice, please.</p><p>Thanks for being with me throughout all the story and remember, it’s within our power to make the user experience more enjoyable!</p><h4>Related articles</h4><ul><li><a href="https://medium.com/airbnb-engineering/recent-web-performance-fixes-on-airbnb-listing-pages-6cd8d93df6f4">React Performance Fixes on Airbnb Listing Pages</a> (2017)</li><li><a href="https://cdb.reacttraining.com/react-inline-functions-and-performance-bdff784f5578">React, Inline Functions, and Performance</a> (2017)</li><li><a href="https://medium.com/@esamatti/react-js-pure-render-performance-anti-pattern-fb88c101332f">React.js pure render performance anti-pattern</a> (2016)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1aea20fb3f0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/wix-engineering/two-mistakes-in-react-js-we-keep-doing-over-and-over-again-b1aea20fb3f0">Two mistakes in React.js we keep doing over and over again</a> was originally published in <a href="https://medium.com/wix-engineering">Wix Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>