<?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 Matan Borenkraout on Medium]]></title>
        <description><![CDATA[Stories by Matan Borenkraout on Medium]]></description>
        <link>https://medium.com/@matanbobi?source=rss-747a54ede665------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*IhC3FewlU5GBVCuzRVLtfg.jpeg</url>
            <title>Stories by Matan Borenkraout on Medium</title>
            <link>https://medium.com/@matanbobi?source=rss-747a54ede665------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 15 Nov 2026 12:36:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@matanbobi/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[A tip for an amazing code review]]></title>
            <link>https://medium.com/@matanbobi/a-tip-for-an-amazing-code-review-330df5157652?source=rss-747a54ede665------2</link>
            <guid isPermaLink="false">https://medium.com/p/330df5157652</guid>
            <category><![CDATA[code-review]]></category>
            <category><![CDATA[engineering]]></category>
            <dc:creator><![CDATA[Matan Borenkraout]]></dc:creator>
            <pubDate>Wed, 17 Aug 2022 07:22:52 GMT</pubDate>
            <atom:updated>2026-03-18T14:21:16.984Z</atom:updated>
            <content:encoded><![CDATA[<p>This post is also available on my personal site at:<br><a href="https://matanbobi.dev/posts/a-tip-for-an-amazing-code-review">https://matanbobi.dev/posts/a-tip-for-an-amazing-code-review</a></p><p>As engineers, we review code on a daily basis. The code review process is something we’re used to, but maybe we’re underestimating the value it gives us?<br>In code reviews we share our knowledge, we make an impact and most importantly, we create common ownership over our code.<br>Good code review process aims to solve a few pain points, in this post I’ll cover the first point in a series of 4 points.</p><h4>Building the right thing</h4><p>Let’s say we were constructors (real constructors, with cement and everything 😅) and a new client asked us to build them the house of their dreams.<br>The client described us what they wanted, and we went straight to work.<br>1.5 years later, we shipped them an amazing house:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*u5FOaf7_mx9FyQF0.jpg" /><figcaption>The house we built, looks good doesn’t it?</figcaption></figure><p>When our clients entered the house, they were shocked. The house wasn’t even close to what they wanted. Too many rooms, they wanted a single floor house and the infinite pool was supposed to to be on the left.<br>Looks like going “straight to production” wasn’t a good idea. We could have maybe create a model of the house and verify it satisfies our clients? Maybe even a sketch could work.</p><p>Same goes for a pull requests we work on. In order to “get it right the first time” (TM), we should aim to present a clear vision of what we’re going to implement and how we’re going to implement it.<br>This can either be by presenting the technical design ahead or even creating a draft PR (pull request) with a small prototype. The main thing to remember here is that if we’re presenting an early draft or unpolished work, we should notify our reviewer about that (in the PR’s description).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZG2zqEmBaY8XBbJIpqTa6A.png" /><figcaption>Draft PR in GitHub</figcaption></figure><p>Another good approach to verifying we’re building the right thing is to enforce tests for every PR. When reviewing the code, starting with the test cases to understand what this PR is covering can be a good approach.</p><p>Lastly, when we open the pull request, we should not forget to attach a ticket and describe what we’re doing. This will help our reviewer get background about why and what we’re trying to solve.</p><h4>Summary</h4><p>This was a quick tip about code reviews, I’ll do my best to continue writing more tips related to code reviews :)<br>If you have any questions, feel free to ask here or on <a href="https://twitter.com/matanbobi">Twitter</a>.</p><p>Thanks!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=330df5157652" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[To unit, or integration? That is the question]]></title>
            <link>https://medium.com/@matanbobi/to-unit-or-integration-that-is-the-question-1228bb3561b1?source=rss-747a54ede665------2</link>
            <guid isPermaLink="false">https://medium.com/p/1228bb3561b1</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[react-testing-library]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Matan Borenkraout]]></dc:creator>
            <pubDate>Sat, 30 Apr 2022 16:34:25 GMT</pubDate>
            <atom:updated>2022-05-07T18:51:23.682Z</atom:updated>
            <content:encoded><![CDATA[<h3>To unit, or not to unit? That is the question</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PvT4bm2MslQyv16BQoNruw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@imkirk?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Iewek Gnos</a> on <a href="https://unsplash.com/@imkirk?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>This post is also available in my personal site:<br><a href="https://matan.io/posts/to-unit-or-integration">https://matan.io/posts/to-unit-or-integration</a></p><p>If you’re using one of the <a href="https://testing-library.com/">testing-library</a> packages, you’re probably already familiar with the term “implementation details” and why we should not test those. If you’re not familiar with that term, here’s a quick explanation:</p><h3>Kent C. Dodds 🌌 on X (formerly Twitter): &quot;The more your tests resemble the way your software is used, the more confidence they can give you. / X&quot;</h3><p>The more your tests resemble the way your software is used, the more confidence they can give you.</p><p>Since implementation details aren’t something our users see, use or know about, they should not be part of our tests. I want to specifically emphasize one part of this sentence and the types of tests we need to adhere to it.</p><h4>The way our software is used</h4><p>Before talking about “the way our software is used”, it’s important to understand who are our users.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cKA1ET7iFGXVsnEz4yVApQ.png" /><figcaption>We have two users: engineers and clients.</figcaption></figure><p>Usually when we think about the way our software is used, we think about our clients, the ones going from page to page, clicking the buttons and filling out forms. We should not forget about the other type of users: our fellow engineers, using the component’s API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FM9IPGrudGhOCxhK74mJ0A.png" /><figcaption>Different usage types, engineers use API (props and callbacks), clients use interactions and view the UI</figcaption></figure><p>In order to resemble the way clients use our software, we should write integration tests that include pages, many components that interact with each other and also not forget to include the “plumbing” (eg. Data providers, Actions, Reducers and many more). <br>I mean, I’ve never seen an app with one button, have you?</p><p>This part of the principal leans hard towards “integration testing is the only valid approach”.</p><p>What does it mean for unit tests? are they useless? Well, no, they are not.</p><p>Our second type of users are engineers, and the way they use our software is entirely different. <br>Let’s say we build a TextField component. That component will be visible to our clients, but the ones actually using that TextField will be our fellow engineers.<br>In order to resemble the way they use our software, we should write unit tests that cover the API of that component. <br>We should render only that component and verify that it works as a standalone while making sure that it succeeds in providing the entire API it promises to its users.</p><p>The bottom line is that we should understand what’s the best way to imitate our user’s behavior and leverage our tools accordingly.<br>When we have “shared” components which are widely used within our project by other developers, we should be unit testing them to verify that their API works perfectly.<br>When we have a feature combining multiple components, we should use integration test to verify that this feature works perfectly.</p><h4>Final words</h4><p>I decided to write this down because I received this question multiple times as a Testing Library maintainer. Hopefully, you now understand why unit tests are still relevant even if we follow the important principal of “testing our software the way it’s used”.</p><p>Last but not least,<br>I hope everyone’s feeling well and keeping themselves safe!<br>If you have any questions, I’m here and also on <a href="https://twitter.com/matanbobi">Twitter</a>. <br>Feel free to ask or comment, I’d love to hear your feedback or help with any dilemmas you have :)</p><p>Thanks,<br>Matan.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1228bb3561b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use Emojis as Favicons]]></title>
            <link>https://medium.com/@matanbobi/how-to-use-emojis-as-favicons-371795662465?source=rss-747a54ede665------2</link>
            <guid isPermaLink="false">https://medium.com/p/371795662465</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[website]]></category>
            <dc:creator><![CDATA[Matan Borenkraout]]></dc:creator>
            <pubDate>Mon, 28 Feb 2022 12:15:22 GMT</pubDate>
            <atom:updated>2022-03-07T08:01:45.548Z</atom:updated>
            <content:encoded><![CDATA[<p>This post is also available in my personal site:<br><a href="https://matan.io/posts/how-to-use-emojis-as-favicons">https://matan.io/posts/how-to-use-emojis-as-favicons</a></p><p>If you wanted to use an Emoji as a favicon but wasn’t sure how to do it or if it’s supported, then here are all the details you need to know.</p><h4>Support</h4><p>To simply use an emoji as a Favicon, we’ll need to use an SVG as our Favicon. This is supported in all ever-green browsers besides <strong>Safari</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T3PGPRKNngPBfe_24nvT7A.png" /><figcaption>A browser support matrix taken from <a href="https://caniuse.com/link-icon-svg">https://caniuse.com/link-icon-svg</a></figcaption></figure><h4>Method</h4><pre>&lt;link rel=&quot;icon&quot; type=&quot;image/svg+xml&quot; sizes=&quot;any&quot;        href=&quot;data:image/svg+xml,&lt;svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22&gt;&lt;text y=%22.9em%22 font-size=%2290%22&gt;🥬&lt;/text&gt;&lt;/svg&gt;&quot;/&gt;</pre><p>Adding this code snippet to your head section will give you a nice emoji favicon. Cool thing about this is that using sizes=&quot;any&quot; gives us an option to support all resolutions and all sizes in just one line. This works only because we’re using image/svg+xml and SVG is “Scalable Vector Graphic”.</p><p>Last but not least,<br>I hope everyone’s feeling well and keeping themselves safe.<br>If you have any questions, I’m here and also on <a href="https://twitter.com/matanbobi">Twitter</a>. Feel free to ask or comment, I’d love to hear your feedback or help with any dilemmas you have :)</p><p>Thanks,<br>Matan.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=371795662465" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Caring as a Service (CaaS)]]></title>
            <link>https://medium.com/@matanbobi/caring-as-a-service-caas-7d04e7c9ca57?source=rss-747a54ede665------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d04e7c9ca57</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[teamwork]]></category>
            <category><![CDATA[team]]></category>
            <dc:creator><![CDATA[Matan Borenkraout]]></dc:creator>
            <pubDate>Tue, 14 Dec 2021 15:36:48 GMT</pubDate>
            <atom:updated>2022-03-07T08:02:36.565Z</atom:updated>
            <content:encoded><![CDATA[<p>This post is also available in my personal site:<br><a href="https://matan.io/posts/caring-as-a-service">https://matan.io/posts/caring-as-a-service</a></p><p>Some people tend to think that our work as Software Engineers is all about coding. I can’t disagree more.</p><p>In our daily work, we are involved in many situations that may affect other people around us and that’s why I believe caring should be a major part of our work.</p><p>We continuously iterate on our code to make it better (admit it or not, you care for your code), can we incorporate caring in our daily work even when it’s not related to the code we write? How can we be more active when it relates to caring?</p><p>Caring is “Feeling or showing concern for or kindness to others” (<a href="https://www.merriam-webster.com/dictionary/caring">Merriam Webster</a>). We have a lot of opportunities to show we care in our day to day life, we just need to pay attention to them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GmWCtsaKPoHib8_y" /><figcaption>Photo by <a href="https://unsplash.com/@brett_jordan?utm_source=medium&amp;utm_medium=referral">Brett Jordan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Caring in your daily work</h4><p>In many cases someone else will have to read the code we write so the fact we can understand what is going on is not enough. Consider this quote from the book “Clean Code”:</p><blockquote>“Clean code always looks like it was written by someone <br> who cares” — Micheal Feathers</blockquote><p>Caring about others (and your future self) is crucial for your code to be useful over time.</p><p>Another aspect of caring in our daily work is considering the fact that your work is part of a bigger project. This means that if you care about the success of the project, you need to make sure you document your work and share your knowledge when needed, so other people can support what you did. Same goes the other way around when you’ll need to support what your teammates did. Caring about the project will create common ownership among all of the team and not just individuals.</p><h4>Caring in your team</h4><p>Development projects usually involve people with different functions: from QA, to UX designers, Backend devs, Frontend devs, Product managers etc. We can also assume that your team may be constructed of different seniority levels within the same functions.</p><p>By caring about other people even if we are not responsible for their part of the work, we can improve the velocity of the greater team and reduce friction. Sometimes it means doing a little extra work that may not be “in our court” like helping the QA or the UX Designer. Sometimes it means explaining what you did another time so it’s clear and sometimes it is providing feedback or talking to someone having a bad day.</p><p>Being proactive by asking, commenting and sharing your opinion and interest will take your caring to the next level and will encourage others to do the same.</p><h4>Caring in the community</h4><p>On top of our work, we are all part of developer communities. <br>Contributing back to the community is the ultimate form of caring since it doesn’t necessarily benefit you.</p><p>One great way to show you care is to contribute to open source projects.<br>Using your free time in order to provide others with a way to get things done easily and quickly without expecting anything in return means caring.</p><p>Contributing to OSS can come in many forms.<br>You encountered an issue? Try to find the time to submit a PR. If you don’t have the time, open an issue, let everyone know that you found something.<br>You loved a feature? reach out, tell people you love it. There are many communication channels nowadays (from discord, to twitter to even GitHub discussions) so you can reach out to almost anyone.</p><p>I got into open-source by showing I care and answering open issues in <a href="https://github.com/testing-library/">Testing-Library</a>. I have to admit, it felt really good. The small appreciation from someone you helped, means a lot.</p><h4>Final note</h4><p>Caring takes work. You need to be proactive and mindful to show you care, but I promise you, it is definitely worth it. It will make you and everyone around you better at what you do.</p><p>Last but not least,<br>I hope everyone’s feeling well and keeping themselves safe!<br>If you have any questions, I’m here and also on <a href="https://twitter.com/matanbobi">Twitter</a>. Feel free to ask or comment, I’d love to hear your feedback or help with any dilemmas you have :)</p><p>Thanks,<br>Matan.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d04e7c9ca57" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why you should stop using the “container/presentational” pattern in Redux]]></title>
            <link>https://medium.com/@matanbobi/why-you-should-stop-using-the-container-presentational-pattern-in-redux-29b112406128?source=rss-747a54ede665------2</link>
            <guid isPermaLink="false">https://medium.com/p/29b112406128</guid>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[frontend]]></category>
            <dc:creator><![CDATA[Matan Borenkraout]]></dc:creator>
            <pubDate>Tue, 03 Aug 2021 15:50:52 GMT</pubDate>
            <atom:updated>2026-03-18T14:21:48.165Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>TL;DR:<br>The redux style guide has an important rule: “Connect More Components to Read Data from the Store”. This rule has some important performance aspects that are covered with an example in this post.</blockquote><p>This post is also available in my personal site:<br><a href="https://matanbobi.dev/posts/stop-using-container-presentational">https://matanbobi.dev/posts/stop-using-container-presentational</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NH2Nz0YSedkhlgwe" /><figcaption>Photo by <a href="https://unsplash.com/@frankiefoto?utm_source=medium&amp;utm_medium=referral">frank mckenna</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The “Container/Presentational” Pattern used to be the best practice when using redux or any other store management package.<br>It was explained thoroughly by <a href="https://twitter.com/dan_abramov">Dan Abramov</a> and <a href="https://twitter.com/chantastic">Michael Chan</a>. <br>If we want to keep it short, a container usually holds the data fetching logic and data access to store. On the other hand, a presentational component is more generic and just present the data it gets as props.<br>This pattern was common before React Hooks were introduced and probably every developer using React with classes has seen or used it.</p><p>But in the world of hooks, this approach can cause serious performance issues (we will cover those later on).<br>Moreover, the <a href="https://redux.js.org/style-guide/style-guide#connect-more-components-to-read-data-from-the-store">Redux best practices</a> now suggests we should connect more components to read directly from the store (which is quite the opposite to this pattern).</p><blockquote>“Prefer having more UI components subscribed to the Redux store and reading data at a more granular level. This typically leads to better UI performance, as fewer components will need to render when a given piece of state changes.” (The redux docs)</blockquote><p>But, what’s the reason behind this rule?</p><h4>Our example app</h4><p>I’ve built a small app with a sidebar fetching all the Pokemons (with a Select that decides how many Pokemons to fetch), and a right box showing the selected Pokemon. Clicking on a Pokemon name at the left, will change the image and fetch the relevant data.<br>The UI looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*h-RYVcTQ13w_qfaxjSfphw.png" /></figure><p>In the first approach, I decided to use <a href="https://react-redux.js.org/api/connect">connect</a> on a container, query all the data from the store and also mapDispatchToProps so I’ll be able to dispatch some data fetching. <br>I passed the data to my components using props (the example uses styled-components but the actual styles were left behind):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c20ae53d2aa172b2b730b97c84044bc/href">https://medium.com/media/8c20ae53d2aa172b2b730b97c84044bc/href</a></iframe><p>My components just fetch the data and show it based on the props.<br>I opened the React profiler, recorded a click on a Pokemon name and saw the renders that it triggered. <br>Here’s the screenshot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ID4K9a-lqnoVPF_1hoU_VA.png" /></figure><p>What do we see here?<br>When clicking on a Pokemon name on the left sidebar, we initiated two renders. In the first one we see the PokemonsSidebar was rendered and it took 1ms. But, why was it even rendered? It didn’t change, nor did it’s props. The reason for that is that the parent component was rendered because of a change in the redux store, so all of it’s children should also render.<br>We can also see that the whole Render duration was 13.6ms, that’s because inside the PokemonsSidebar we have 150 li‘s that rendered again for no reason because their parent re-rendered.</p><p>In the second approach, I refactored my code to useSelector and useDispatch. My presentational components will be connected directly to the store and dispatch the actions.<br>Here’s my component’s code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b6481e845fbcfccd4ca74c122a330ac/href">https://medium.com/media/2b6481e845fbcfccd4ca74c122a330ac/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cdebd37c5e752b332e55a330a4e7bc19/href">https://medium.com/media/cdebd37c5e752b332e55a330a4e7bc19/href</a></iframe><p>Let’s see the profiler screenshot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zbzsw3HIqfiu3nATuQcTEQ.png" /></figure><p>As we can see here, the PokemonsSidebar didn’t re-render because it wasn’t subscribed to the selectedPokemon data from the store, thus all of it’s children didn’t re-render. The Render duration this time is only 0.9ms (compared to 13.6ms)!</p><p>These numbers may sound negligible but that’s just an example. My app isn’t complicated and there’s just one component that shouldn’t render (and it’s children). What if I had more components? and my components had a heavy render?</p><h4>Why does it happen?</h4><p>Since we’re using function components, whenever our parent component renders, <a href="https://blog.isquaredsoftware.com/2020/05/blogged-answers-a-mostly-complete-guide-to-react-rendering-behavior/#standard-render-behavior">the whole tree is marked for render</a>. React then recurses over all children and tries to render them. If our function components aren’t wrapped with React.memo they will automatically re-render even if their props or state didn’t change. We need to bear in mind that memoization also <a href="https://medium.com/swlh/should-you-use-usememo-in-react-a-benchmarked-analysis-159faf6609b7">has some performance impact</a> so wrapping all of our components with React.memo isn’t always the best approach.</p><h4>Disclaimer</h4><p>As you can understand from the last section, this isn’t a Redux only issue, but rather a React behavior. The “container/presentational” pattern can still be a valid solution as long as the impact is taken into consideration.<br>It’s important to note that this isn’t just a useSelector vs connect issue. I’ve seen examples creating a container with lots of useSelectors just aiming to mimic this “container” approach and I’ve also seen examples of connect on many components.</p><h4>Summary</h4><p>In this post, we’ve covered an important rule that was somewhat hidden inside the whole Redux style guide. If you still haven’t read the style guide, I urge you to do it. It contains many rules that will make your work with Redux straightforward and clear.</p><p>I hope everyone’s feeling well and keeping themselves safe!<br>If you have any questions, I’m here and also on <a href="https://twitter.com/matanbobi">Twitter</a>. Feel free to ask or comment, I’d love to hear your feedback!</p><p>Thanks,<br>Matan.</p><h4>Read More:</h4><p><a href="https://github.com/MatanBobi/modern-redux-practices">The repo containing this example</a> <br><a href="https://redux.js.org/style-guide/style-guide">The Redux best practices</a><br><a href="https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0">Presentational and Container Components</a> by Dan Abramov<br><a href="https://medium.com/@learnreact/container-components-c0e67432e005">Container Components</a> by Michael Chan</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29b112406128" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introducing: The Async Cookie Store API]]></title>
            <link>https://medium.com/@matanbobi/introducing-the-async-cookie-store-api-89cbecf401f?source=rss-747a54ede665------2</link>
            <guid isPermaLink="false">https://medium.com/p/89cbecf401f</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Matan Borenkraout]]></dc:creator>
            <pubDate>Fri, 16 Oct 2020 21:30:38 GMT</pubDate>
            <atom:updated>2026-03-18T14:22:34.836Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>TLDR:<br>The Cookie Store API is a new browser API built to expose cookies to service worker and offer an asynchronous alternative to document.cookie. It’s available in Chrome Browser starting from version 87.</blockquote><p>This post is also available in my personal site:<br><a href="https://matanbobi.dev/posts/introducing-the-async-cookie-store">https://matanbobi.dev/posts/introducing-the-async-cookie-store</a></p><p>Are you sick and tired of weird ways to get cookies fromdocument.cookie ? Hate it that you don’t know whether the cookie you set was actually saved or not? Introducing: Cookie Store API, available on Chrome version 87!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Uv0f_gvCuOvhPNs1" /><figcaption>Photo by <a href="https://unsplash.com/@starvingartistfoodphotography?utm_source=medium&amp;utm_medium=referral">Christina Branco</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Motivation</h4><p>We all use HTTP Cookies almost daily, but working with them was never an easy task. <br>The cookies interface is overly complexed and contains performance issues. Saving all of the cookies in document.cookie which is part of the Document Object Model from October 2000, seems like a pattern that doesn’t correspond to the javascript we write these days.</p><p>The Cookie Store API aims to improve this by providing an asynchronous alternative to document.cookie and exposing HTTP cookies to service workers, which will also benefit performance. It’s available on Chrome Browser starting from version 87 but still didn’t land in any other major browsers.</p><h4>Get Cookies</h4><p>Getting a cookie always looked odd to me. Why do I have a full string containing all of the cookies? Getting a specific cookie always seems like an over-complex solution, using some regex or looping over the document.cookie value. In fact, all of us who need cookies probably have this util taken from some <a href="https://stackoverflow.com/a/24103596/4232673">StackOverflow answer</a> in their codebase:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*xSFsHux-qpIgDsID2iLAZA.png" /></figure><p>In the new way, all we need to do is use the cookieStore object and call its get function. Don’t forget that this returns a promise so you await for its result and if something wrong happened, it would throw an error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*78dyOtivZ4MQDi0Vyr1kLQ.png" /></figure><p>No more looping over a cookies string! Amazing!</p><h4>Set Cookie</h4><p>Don’t you just hate setting a cookie? The API seems so old-fashioned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*SonmZm0kfeemXS4HR3v1_w.png" /></figure><p>Following what we wrote about getting cookies, the setCookie util probably looks somewhat like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*JohQEp6XBPiHpdAPkJk-gA.png" /></figure><p>After doing that, we’d probably also want to know that the cookie was successfully created. So we’ll use the getCookie util from before and loop over the cookies string to find that cookie.</p><p>In the new API, what you’ll need to do is use the cookieStore object and call the set function with the params, that’s all.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*7BXhD9a1ZejR5cDLo_1HCA.png" /></figure><p>After calling that function, as long as we didn’t get to the catch block, we can be 100% sure that the cookie was saved successfully, and we don’t need to loop over anything or call cookieStore.get to see that it was saved.</p><h4>Delete Cookies</h4><p>To delete the cookie, we probably had something similar to this util:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*uPqUHpLhCno_pkFhfR6fZw.png" /></figure><p>It will basically set the cookie date to an old date and count on the browser to delete it since it’s already expired.</p><p>In the new way, you’ll need to call the delete function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*JLqioxOAEb4Rxb6Emgsi9A.png" /></figure><p>Once again, as long as we didn’t get to the catch block, you can 100% be sure that the delete happened.</p><h4>Monitoring Cookies</h4><p>A cool thing you can do with the new Cookie Store API is know when the cookie object was changed and act on it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*Fi8HFd7jUitpqj6FfO5-QA.png" /></figure><h4>Summary</h4><p>It looks like the Chrome team tackled a problem we took for granted for a long time, and I do believe that this is great progress towards a better web!<br>If you’d like to read more, you can visit the <a href="https://wicg.github.io/cookie-store/">Cookie Store API Draft</a>.</p><p>I hope everyone’s feeling well and keeping themselves safe!<br>If you have any questions, I’m here and also on <a href="https://twitter.com/matanbobi">Twitter</a>. Feel free to ask or comment, I’d love to hear your feedback!</p><p>Thanks,<br>Matan.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89cbecf401f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The hidden magic of Main Thread Scheduling]]></title>
            <link>https://medium.com/@matanbobi/the-hidden-magic-of-main-thread-scheduling-5f20b7803293?source=rss-747a54ede665------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f20b7803293</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Matan Borenkraout]]></dc:creator>
            <pubDate>Sun, 10 May 2020 11:48:28 GMT</pubDate>
            <atom:updated>2026-03-18T14:23:55.359Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>TL;DR:<br>Scheduling is a mechanism introduced lately by the React team to manage and prioritise tasks in the browser. It has become a case study for Google Chrome Dev team, to create a “Main Thread Scheduling” API. <br>This is groundbreaking work done by both of the teams. In this article I’ll talk about the APIs, how to use them, and how they will make a difference for our users!</blockquote><p>This post is also available in my personal site:<br><a href="https://matanbobi.dev/posts/introducing-the-async-cookie-store">https://matanbobi.dev/posts/introducing-the-async-cookie-store</a></p><p>If you were a part of the Frontend community for the past year and a half, the term “Concurrent” appears in almost every second tweet. <br>It all started with <a href="https://twitter.com/dan_abramov">Dan Abramov</a>’s talk <a href="https://reactjs.org/blog/2018/03/01/sneak-peek-beyond-react-16.html">Beyond React 16</a> at JSConf Iceland 2018. Dan showed how the React team built a generic way to ensure that high-priority updates don’t get blocked by a low-priority update. The React team called this mechanism “Time Slicing” and it was based on a <a href="https://www.npmjs.com/package/scheduler">Scheduler package</a> they created.</p><p>This scheduler is called the “Userspace Scheduler” and was later used as a case study for Google Chrome developers for their work on a built-in scheduling mechanism.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ogxCiI3TewGbU-M2" /><figcaption>Photo by <a href="https://unsplash.com/@alexandar_todov?utm_source=medium&amp;utm_medium=referral">Alexandar Todov</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>The Problem</h4><p>Let’s take Lin Clark’s analogy from her <a href="https://www.youtube.com/watch?v=ZCuYPiUIONs">talk</a> in React Conf 2017 and compare our code to a Project Manager. Our project manager has 1 worker, the browser, but our worker is pretty busy, he’s not 100% dedicated to our JavaScript code. It uses one thread to run our code, perform garbage collection, layout, paint, and more. <br>This issue buried the main problem: long-running JavaScript functions can block the thread and cause our worker to tip the balance and miss layout, paints, and more. This is a steep slope that immediately leads to an unresponsive page and a bad user experience.</p><h4>The Solution</h4><p>This problem is usually tackled by chunking and scheduling main thread work. In order to keep the browser responsive at all times, you break long tasks to smaller ones and yield back the control to the browser after an appropriate time. The time is calculated based on the current situation of the user and the browser. <br>But wait, how will I know to split the work based on time on my own? How do I even yield back control to the browser? 🤔 <br>To solve these problems we have Userspace Schedulers. So what are they?</p><p><strong>Userspace Scheduler</strong><br>A generic name for JS libraries built-in attempt to chunk up main thread work and schedule it at appropriate times. These libraries are responsible for doing the work and yielding the control back to the browser without blocking the main thread.<br>The main goal: Improve responsiveness and maintain high frame-rate. <br>The main examples are <a href="https://www.npmjs.com/package/scheduler">React’s Scheduler package</a> and Google Maps Scheduler.<br>These schedulers have been effective in improving responsiveness but they still have some issues, let’s go over them:</p><ol><li>Determining when to yield to the browser — Making intelligent decisions of when to yield is difficult with limited knowledge. As a Userspace scheduler, the scheduler is only aware of what’s happening in its own area.<br>The React’s scheduler, for example, defaults to 30 FPS for every unit of work (which means around 1000ms/30=33.333ms) and adjusts it to higher a FPS rate if possible. Having said that, React’s scheduler still checks between frames to see if there’s any user blocking task pending on the main thread and if there is, it yields back control to the browser. React does that by using scheduling.isInputPending(), we will talk about this function in the APIs section.</li><li>Regaining control after yielding — When regaining control back from the browser, we will have to do the work of the same priority without returning back to the paused task until finishing the other work. That happens because we yield to the event loop and write a callback but there can already be callbacks waiting for that priority.</li><li>Coordination between other tasks — Since userspace schedulers don’t control all tasks on the page, their influence is limited. For example, the browser also has tasks to run on the main thread like garbage collection, layout, etc. and userspace schedulers can’t impact these tasks.</li><li>Lack of API to schedule chunks of the script — Developers can choose from setTimeout, postMessage, requestAnimationFrame, or requestIdleCallback, when choosing to schedule tasks. All of these have a different impact on the event loop and require a thorough knowledge of how it works.<br>The React’s scheduler for example uses setTimeout as shown <a href="https://github.com/facebook/react/blob/3c7d52c3d6d316d09d5c2479c6851acecccc6325/packages/scheduler/src/forks/SchedulerHostConfig.default.js#L47">here</a>.</li></ol><p><strong>Main Thread Scheduling API</strong>:<br>Since all current solutions have limitations, the Chrome team decided to create API’s for scheduling main thread work. These APIs are all gathered under the “Main-thread Scheduling API” title and are currently an experimental feature not yet deployed to production nor beta version.</p><h4>How can we try it?</h4><p>To get the new Main Thread Scheduling APIs we need Chrome version <strong>82.0.4084.0</strong> and higher.</p><p>This version is available in Chrome’s beta version or in Dev and Canary versions. I recommend downloading the Chrome Canary version since it can live alongside our current Chrome version. A download link can be found <a href="https://www.google.com/chrome/canary/">here</a>.<br>Once downloaded, we need to turn on the feature-flag called Experimental web platform APIs here: chrome://flags/#enable-experimental-web-platform-features</p><h4>API’s</h4><p>scheduler.yield: When calling this function, we will yield to the event loop, such that a continuation task will run after the user agent services higher priority work, but <em>before</em> tasks of the same priority are allowed to run.<br>This function will return a Promise which will be resolved after the event loop services the higher priority work. We will also be able to specify a priority to the function scheduler.yield(‘high’) stating we want control after tasks with this priority or higher were executed.</p><p><a href="https://wicg.github.io/is-input-pending/">scheduling.isInputPending()</a>: This function will let us understand whether we have any pending input events waiting in the event loop and in that case we can yield back to the browser so it will handle these input events. This function is <a href="https://github.com/facebook/react/blob/3c7d52c3d6d316d09d5c2479c6851acecccc6325/packages/scheduler/src/forks/SchedulerHostConfig.default.js#L127">actually being used in React’s Scheduler</a>.</p><p>requestPostAnimationFrame: This API isn’t implemented yet and is more of a draft API. This API will act as a bookend for the requestAnimationFrame functionality, an “after paint” callback. <br>To understand this — The callback of requestAnimationFrame runs just prior to the rendering and the callback of requestPostAnimationFrame will run <em>immediately</em> after the rendering. This can be used to get a head-start on long running task and starting to create the next frame as soon as possible.</p><p>TaskController: This API is the main API for controlling tasks, it contains a signal object with the following structure:</p><pre>{<br>  aborted: false,<br>  onabort: null,<br>  onprioritychange: null,<br>  priority: &quot;user-visible&quot;<br>}</pre><p>The TaskController Object inherits its functionality from <a href="https://developer.mozilla.org/en-US/docs/Web/API/AbortController">AbortController</a> and the signal inherits its functionality from <a href="https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal">AbortSignal</a> so when using it, we will be able to abort a task that wasn’t executed yet.<br>API looks like:<br>const<em> </em>controller<em> </em>=<em> </em>new<em> </em>TaskController(“background”)<br>and to get the signal we simply write controller.signal.</p><p>scheduler.postTask : This API can be used to post a task with a priority or a delay. <br>The postTask function accepts a callback function and a signal. This signal can either be the one created from the TaskController or just an object with priority property or delay priority containing a number. <br>The API shape is similar to other async API’s (<a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API">fetch</a> for example): scheduler.postTask(callbackFunction, { priority: &#39;background&#39; })</p><p>It’s important to note that creating a callback with background priority can also be done by using requestIdleCallback. Having said that, posting and managing multiple priorities is much more complicated without these API’s.</p><p>There are more API’s that fall under the umbrella of Main Thread Scheduling but these are the ones I found important to note here.</p><h4>Example</h4><p>An important note is that I’m <strong>not </strong>using React’s Concurrent Mode. I’m trying to show a solution based only on the new Scheduling API and not on React’s Userspace scheduler (disclaimer: even the non Concurrent Mode React works with a scheduler but it doesn’t contain the time-slicing features).</p><p>Another small note, I’ve based my example project on <a href="https://twitter.com/PhilippSpiess">Philipp Spiess</a>’s project for “Scheduling in React” <a href="https://philippspiess.com/scheduling-in-react/">post</a>.</p><p>Here’s a gif showing the app in action, try to look at all the details on the screen and what happens when I try to type:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vPkQKysVbUpu2SyIJDyzRQ.gif" /><figcaption>My mini Pokedex app</figcaption></figure><p>On the screen, we see a header with an animation working with requestAnimationFrame (rAF), a search input, and a few pokemon (there are actually 200 rendered).<br>So why does it get stuck? 🤔<br>What happens is as follows: on every keypress in the input, the whole pokemon list renders (I passed the search string to every pokemon so we will mark the search substring) and every pokemon has a synchronous timeout (a while loop of 2ms). <br>As we said, in my app I have 200 pokemon, leading each keypress to cause a render of about 400ms. To top it up, on the event handler I also simulated a synchronous heavy computation function of 25ms.</p><p>Let’s look at a performance screenshot of what’s happening:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VnSNuV2nBe92UR-_mD1USg.png" /></figure><p>In the red box, you can see timings that I added or React added by itself. <br>The yellow box contains the call stack breakdown for each keypress.</p><p>Here’s a quick breakdown of what’s happening:<br>Every keypress leads to a long render (about 400ms), causing a Frame Drop(this can be inferred from the red triangle I wrapped with a blue circle).<br>Frame drop happens when the main thread is too busy with running our JavaScript code so it doesn’t get the chance to update the UI so the website freezes.<br>Before every render, in the timings section (the red box) we can see a small box I wrapped by green ovals, that’s our heavy computation function, it takes around 25ms as we can see in the tooltip. But sometimes, we don’t need that heavy computation to happen right away, maybe we can do it later. With Main Thread Scheduling API, we can do exactly that.</p><p>To do that, we need to change our event handler. At the moment it looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*YsJNYSaRds01sZdcj4cIIQ.png" /><figcaption>Current event handler implementation</figcaption></figure><p>Let’s use postTask and see the performance analysis:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*UHVoNNImsfwpp1fhvJA0lA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AsU25WxW22V3gvMEreGLPQ.png" /></figure><p>So what did we see?<br>Our heavy computation function now happens at the end (wrapped in the timings section with a green oval), after all the renders happen. The main difference is for our users, instead of waiting 3800ms for the UI to be interactive, they now wait 3600ms. That’s still not so good but even 200ms is a difference.</p><p>Another amazing feature is to be able to cancel a task if it wasn’t executed yet.<br>In the previous example, we had a heavy computation function happening on every event, what if we would want it to happen only for the last event?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Fo4QdExJKKlhvgZyvlMSA.png" /><figcaption>The code using TaskController API</figcaption></figure><p>So what’s happening here? here’s a quick explanation:<br>We’re aborting the last signal we had and create a new TaskController every time we enter the event handler. That way we cancel all the tasks with the aborted signal attached to them. Below we can see the performance screenshot for this code, inside the timings section in a green oval we see that only the last task we created was executed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rclyRtVu5ihvfGjAAJ4xDA.png" /></figure><h4>Summing it up:</h4><p>We live in exciting times for the web development community. It looks like everyone involved truly aims for a better web and a better experience for our users.<br>I hope everyone’s feeling well and keeping themselves safe!<br>If you have any questions, I’m here and also on <a href="https://twitter.com/matanbobi">twitter</a>, feel free to ask or comment, I’d love to hear your feedback!</p><p>Thanks for reading!<br>Matan.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f20b7803293" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom rendering in React Testing Library Done Right]]></title>
            <link>https://medium.com/@matanbobi/custom-rendering-in-react-testing-library-done-right-e260e01ba6f7?source=rss-747a54ede665------2</link>
            <guid isPermaLink="false">https://medium.com/p/e260e01ba6f7</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react-testing-library]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Matan Borenkraout]]></dc:creator>
            <pubDate>Sun, 12 Apr 2020 20:42:10 GMT</pubDate>
            <atom:updated>2022-03-11T12:31:31.366Z</atom:updated>
            <content:encoded><![CDATA[<p>This post is also available in my personal site:<br><a href="https://matan.io/posts/custom-rendering-rtl">https://matan.io/posts/custom-rendering-rtl</a></p><p>Browsing multiple projects, I encountered a recurring pattern when trying to write a custom render for components that use Providers (React-Redux’s Provider, React-Intl’s IntlProvider for example).<br>This pattern usually looks like this:</p><figure><img alt="renderWithRedux example, it’s a bad practice" src="https://cdn-images-1.medium.com/max/1024/1*gWwLB5BDLIDlpV1cUPT-3A.png" /></figure><p>This function is nice. It creates a utility that lets us call it whenever we want to test a connected component. The only problem is, it’s limited and causes an inconsistent behavior.<br>Usually, our app will work with several Providers, not only one, and this solution becomes squeaky when we try to add more Providers to it. <br>Another thing is that using it will cause inconsistency since we will call renderWithRedux every time instead of calling render as we usually do and we will also import the renderWithRedux from our test-utils file and all the other RTL utils like screen and fireEvent from @testing-library/react.<br>We will probably get something like this:</p><figure><img alt="Importing from both places creates inconsistency" src="https://cdn-images-1.medium.com/max/1024/1*BpyuErDhtDTTSxqzRfRp0A.png" /></figure><p>To fix this, React Testing Library lets us create a custom render function. <br>I have to be clear. This functionality isn’t new, it’s just not well known or used (in most of the projects I’ve seen lately).<br>To create a custom render function, we don’t have to work hard.</p><figure><img alt="Full blown custom render function" src="https://cdn-images-1.medium.com/max/1024/1*f6Gj-WxuI9ImS9t0ANj29A.png" /></figure><p>By doing this, we’ve created a function that uses the Wrapper option of RTL’s render. On top of it all, we also exported all the other functionalities so now we can import our render function and all the other React Testing Library functionality (fireEvent , screen etc.) from the same place.</p><p>Let’s take an example of a simple connected, translated, styled date component (This is an imaginary use case 😅):</p><figure><img alt="A test using the custom render we built" src="https://cdn-images-1.medium.com/max/1024/1*3F9l2-j5bvHOX5jsrxedzQ.png" /></figure><p>We can see that I imported render and screen from our test utils, and this test is actually using all of our Providers: ThemeProvider, React-Redux’s Provider and IntlProvider.</p><p>That’s it! I hope I made everything clear.<br>If you have any questions, feel free to ask.<br>I’m here and also on <a href="https://twitter.com/matanbobi">twitter</a>.<br>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e260e01ba6f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Wait, you’re not using <React.StrictMode>?!]]></title>
            <link>https://medium.com/@matanbobi/wait-youre-not-using-react-strictmode-a9713927a33b?source=rss-747a54ede665------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9713927a33b</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Matan Borenkraout]]></dc:creator>
            <pubDate>Wed, 23 Oct 2019 17:02:55 GMT</pubDate>
            <atom:updated>2026-03-18T14:23:30.818Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>TL;DR</strong> — StrictMode is a feature added in version 16.3 and aimed to help us in finding potential problems in an application, at the moment especially for Concurrent-Mode which is React’s ability to concurrently render, suspend, and resume rendering trees in the background while remaining interactive.</blockquote><p>This post is also available in my personal site:<br><a href="https://matanbobi.dev/posts/wait-youre-not-using-react-strictmode">https://matanbobi.dev/posts/wait-youre-not-using-react-strictmode</a></p><p>Last month on twitter, I encountered a tweet by <a href="https://twitter.com/sebmarkbage">Sebastian Markbåge</a> a React core team member asking developers if their app is running in &lt;StrictMode&gt;:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SkkQIANKBmECsyjwaAo8qA.png" /><figcaption>Taken from Sebastian’s twitter page</figcaption></figure><p>The results blew my mind, 70% of us aren’t using it and never tried it!<br>At the moment, StrictMode helps us adapt our app to ⚡ Concurrent React ⚡ (Will be covered soon). <br>With <a href="https://conf.reactjs.org/">React-Conf</a> just around the corner (24–25/10), we still don’t know what the keynote by <a href="https://twitter.com/tomocchino">Tom Occhino</a> and <a href="https://twitter.com/yuzhiz">Yuzhi Zheng</a> will be about, it looks like Concurrent mode might arrive sooner than we thought.</p><p>In this post I’ll cover all the warnings produced when using StrictMode, how they are related to Concurrent React and what actually is Concurrent React.<br>I promise you that by the end of this post, you’ll probably want to add it to your react app 🙂</p><h4>What is it?</h4><p>React StrictMode is a feature added in version 16.3 and aimed to help us in finding potential problems in an application.<br>If you see warnings in StrictMode, you will likely encounter bugs when trying to use Concurrent React.</p><p>Like Fragment, StrictMode does not render any UI, it only activates checks and adds warnings at runtime.<br>StrictMode checks are done in development mode only and will <strong>not</strong> affect your production build.</p><h4>Whats the motive?</h4><p>Concurrent React is React’s new ability to concurrently render, suspend, and resume rendering trees in the background while remaining interactive (not destroying old trees while rendering the next).<br>Concurrent React’s main features are Time Slicing and a new Scheduler mechanism but it may also come with more features like React Suspense (for asynchronous data fetching) and Caching.</p><p>We know that Facebook are <a href="https://en.wikipedia.org/wiki/Eating_your_own_dog_food">dogfooding</a> Concurrent React for a while now in the new Facebook web (discovered in F8), iterating on bugs and working to get a stable version.</p><p>Just so you’ll get a glance of Concurrent mode’s power, an unstable example of Time-slicing was shown by <a href="https://twitter.com/dan_abramov">Dan Abramov</a> in his talk <a href="https://www.youtube.com/watch?v=nLF0n9SACd4&amp;vl=en">“Beyond React 16”</a> and can be found <a href="https://timeslicing-unstable-demo.surge.sh/">here</a>.<br>The example above shows Time slicing and scheduling, using it in Synchronous mode is the way React works now and using it in Asynchronous mode is an unstable example of Concurrent mode.</p><p>Concurrent mode is actually a different paradigm than the way we wrote JavaScript up until now, we should think of it more as a multi-threaded model, which schedules our work on a priority base.<br>As this paradigm is different, we need time and practice to get rid of old bad habits, trying out StrictMode is a great way to start.</p><h4>How to use it?</h4><p>All you need to do in order to enable StrictMode (from version 16.3) is to wrap the part you want in your app with &lt;React.StrictMode&gt;.<br>You can wrap the whole app or only specific nodes.<br>Here’s an example of wrapping the whole app:</p><figure><img alt="Code example with StrictMode wraps the whole app" src="https://cdn-images-1.medium.com/max/762/1*Ndux6cTfsM3yOgOz5o33SA.png" /></figure><p>Right after doing that you’ll be able to see warnings in your developer tools console.<br>At the moment, StrictMode helps with a few specific issues, we’ll cover them up and see how the warnings look like.</p><h4>Detecting unexpected side effects:</h4><p>Conceptually, React works in two phases, the <strong>Render phase </strong>and the <strong>Commit phase</strong>. <br>The <strong>render phase</strong> is the expensive part, it’s when React decides what changes need to be made to the DOM. In this phase, React will call your render function and run a render lifecycle which includes: constructor, componentWillMount, componentWillReceiveProps, componentWillUpdate, getDerivedStateFromProps, shouldComponentUpdate, render, setState updater functions.<br>The <strong>commit phase</strong> is the part when React flushes the changes (additions, updates, removals) to the DOM, usually a quick phase. In this phase React also calls the componentDidMount and componentDidUpdate lifecycles.</p><p>While these phases will probably stay the same in Concurrent mode, the plan is to break the render phase into small pieces so we will be able to pause and resume the render phase so we won’t block the browser with long renders.<br>In fact, this means that React may trigger a render lifecycle more than once before committing the changes or even trigger a render without committing it (for example an error was caught or a higher order event happened).<br>So we can understand that the lifecycles in the render phase can be called more than one time, therefore it’s important that they will not contain side effects, if they will contain side effects, it may cause memory leaks and invalid state.</p><p>In order to help with that, in development mode only, StrictMode will double invoke the next methods from the lifecycle: constructor, render, setState updater function and getDerivedStateFromProps so you will be able to see if your code breaks or behaves different than how you expected.</p><h4>Identifying components with unsafe lifecycles:</h4><p>The ‘Unsafe Lifecycles’ term was introduced in release 16.3 of React, it means that some of the legacy component lifecycles tend to encourage unsafe coding practices, they were misunderstood and misused in codebases. The main issue is that their potential misuse may be even more problematic for concurrent react (creating side-effects in places that aren’t made for that may cause problems when updating them concurrently). That’s why componentWillMount, componentWillReceiveProps and componentWillUpdate were all flagged with UNSAFE_ prefix.<br>In StrictMode you will get a list of every component that still uses these lifecycles, that comes in handy to ensure that a third party library isn’t using these lifecycles.</p><p>Using unsafe lifecycles will produce this warning:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F06bVcCaUQJvNXImlKpZYg.png" /></figure><p>To help with refactoring your own code, there’s a code-mod that will rename all unsafe lifecycles and add the UNSAFE_ prefix, though keep in mind that this only removes the warning, it doesn’t remove the use of an unsafe lifecycle.</p><pre>npx react-codemod rename-unsafe-lifecycles &lt;path&gt;</pre><h4>Warning about legacy string ref API usage:</h4><p>Although being the convenient way, legacy string refs have several downsides. The main one was that they were resolved synchronously, which means they will create a problem when rendering will happen concurrently.<br>To fix this warning you have two options:<br>From version 16.3, Using <a href="https://reactjs.org/docs/react-api.html#reactcreateref">createRef</a> is the recommended way to create refs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*1jSvQZxRdcqSjzjxVOyDiA.png" /></figure><p>If you’re using an older version, the recommended way is a <a href="https://reactjs.org/docs/refs-and-the-dom.html#callback-refs">callback ref</a> to make the ref creation “asynchronous”.</p><p>Lastly, you can also refactor your component to use <a href="https://reactjs.org/docs/hooks-intro.html">Hooks</a>, and use the <a href="https://reactjs.org/docs/hooks-reference.html#useref">useRef</a> hook.</p><p>Using string refs will produce this warning:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SvGsIz78Rehb9-y97sUskg.png" /></figure><h4>Warning about deprecated findDOMNode usage:</h4><p>React used to support findDOMNode to search the tree for a DOM node given a class instance.<br>There are a few problems with this approach, the first one is that it might cause an issue with refactoring since a parent component used to be aware of it’s children implementation details if it used findDOMNode to get a child element, The second problem is that findDOMNode returns the first child found, but in a world with Fragments we sometimes have multiple children rendered by one component.<br>Using findDOMNode is usually unnecessary since you can always create a ref directly to a DOM node (as we showed previously), if you do need something like findDOMNode, you can create a ref and use <a href="https://reactjs.org/docs/forwarding-refs.html#forwarding-refs-to-dom-components">Ref Forwarding</a> in your custom component in order to get the underlying DOM element.</p><p>Using deprecated findDOMNode will produce this warning:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s_ZmzThB5b4hBiIZYDHWQA.png" /></figure><h4>Detecting legacy context API:</h4><p>This isn’t Concurrent mode related issue but still addressed within StrictMode. React previously shipped with an experimental context API which was error-prone, and will be removed in a future major version. It still works for all 16.x releases but if you’re using it you should migrate to the new Context API.</p><p>Using legacy context API will produce this warning:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SiP5Q7YrBzewQJcosqnD4w.png" /></figure><h4>Summing it up:</h4><p>In this post we covered all the warning you’ll get when using StrictMode but the main issue isn’t really about StrictMode, it’s more about getting rid of old habits that will keep us from not using Concurrent mode when it becomes available (hopefully on 24/10 🤞).<br>Some users may still be blocked from fixing all the changes I’ve covered here like developers using componentWillMount for server side rendering. These issues will probably be addressed by the React team if weren’t addressed already when implementing Concurrent mode in the new facebook. <br>Another type of users that may be blocked are developers still using legacy 3rd party packages, in that case I recommend upgrading packages or replacing them with new ones since they probably aren’t maintained anymore.</p><p>Hope I convinced you to add StrictMode to your app and that you’ve realised what’s coming up for us as React users.<br>If you have any questions, feel free to ask.<br>I’m here and also on <a href="https://twitter.com/matanbobi">twitter</a>.<br>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9713927a33b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React defaultProps is dying, who’s the contender?]]></title>
            <link>https://medium.com/@matanbobi/react-defaultprops-is-dying-whos-the-contender-443c19d9e7f1?source=rss-747a54ede665------2</link>
            <guid isPermaLink="false">https://medium.com/p/443c19d9e7f1</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Matan Borenkraout]]></dc:creator>
            <pubDate>Mon, 29 Jul 2019 10:34:30 GMT</pubDate>
            <atom:updated>2026-03-18T14:23:05.777Z</atom:updated>
            <content:encoded><![CDATA[<p>This post is also available in my personal site:<br><a href="https://matanbobi.dev/posts/react-defaultprops-is-dying">https://matanbobi.dev/posts/react-defaultprops-is-dying</a></p><p>React as we all know it, is changing. As a frontend developer with React experience for the past 3 years, selling me these changes was quite hard. <br>I’m here today as the seller and not as the buyer, hoping I will catch you in the fever I got once I understood what’s behind all these changes :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j0Xw-Tka8tYO4NKxR79HlQ.png" /></figure><p>After the React team announced <a href="https://reactjs.org/docs/hooks-intro.html">Hooks</a>, and pushed functional components as a “solution for all our problems”, this thought ran in my head, why should we use React’s defaultProps and not ES6 Default values for functional components? Then I found this <a href="https://github.com/reactjs/rfcs/pull/107">RFC</a> that pretty much says what the React core team thinks about the idea.</p><p>In this post I’ll cover my thoughts and share some performance conclusions.<br>I’ll start with a simple explanation regarding defaultProps and ES6 Default Values. To avoid confusion, let’s decide to call React defaultProps React def. values and ES6 Default Values ES6 def. values. If you’re already familiar with the syntax, feel free to jump to the conclusions part.</p><h4>React def. values:</h4><p>Since React v15.5, runtime type checking for component’s props moved to a unified package called prop-types. This package gives us the ability to type check a component’s props and give it default values, for example lets look at a Greet component:</p><pre>const Greet = ({firstName, lastName}) =&gt; {<br>  return (&lt;div&gt;{`Hi ${firstName} ${lastName}`}!&lt;/div&gt;)<br>}</pre><pre>Greet.propTypes = {<br>  firstName: PropTypes.string,<br>  lastName: PropTypes.string<br>};</pre><p>If we try to render Greet without giving it props:</p><pre>const Header = props =&gt; {<br>  return &lt;React.Fragment&gt;<br>    &lt;Logo/&gt;<br>    &lt;Greet/&gt;<br>  &lt;/React.Fragment&gt;<br>}</pre><p>We will get something like this:</p><pre>Hi undefined undefined!</pre><p>defaultProps lets us avoid this scenario by setting default values to props:</p><pre>Greet.defaultProps = {<br>  firstName: &#39;John&#39;,<br>  lastName: &#39;Doe&#39;<br>};</pre><p>so when not passing the relevant props we will get:</p><pre>Hi John Doe!</pre><h4>ES6 def. values:</h4><p>Another option we can use in <strong>functional components only</strong>, is setting default values with ES6 Destructuring assignment syntax.<br>Let’s take the Greet component we’ve created above and change it so it will contain default values.</p><pre>const Greet = ({firstName = &#39;John&#39;, lastName = &#39;Doe&#39;}) =&gt; {<br>  return (&lt;div&gt;{`Hi ${firstName} ${lastName}`}!&lt;/div&gt;)<br>}</pre><p>As simple as that.<br>So what should we use?</p><p>As everything is in programming, it’s a tradeoff, let’s see why.</p><h4>Advantages and Disadvantages of React defaults:</h4><p>While using defaultProps is the best practice at the moment, it looks like this will change in the upcoming versions of React.<br>The main advantage defaultProps has is it gives us a unified way of setting default values to props in both class components and functional components. The second advantage is that the syntax is simple and straightforward.<br>The main problem with defaultProps, lies in its implementation.<br>Let’s have a look at React.createElement implementation at the latest stable version (16.8.6).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b05076ea9f825712d0ca8026e4c88f5/href">https://medium.com/media/7b05076ea9f825712d0ca8026e4c88f5/href</a></iframe><p>We can see that some stuff happen when calling to createElement with the props object, but the main issue is the defaultProps check. If we have defaultProps, we iterate over them and check if we already have a value in the props object, in case we don’t have a value we assign it the default. This happens <strong>every time</strong> we call createElement. <br>Let’s have a look at a small timing example I took with the Greet component we just built (The test was made in a development build of React). <br>All I did was adding console.time() at the start of createElement and console.timeEnd() at the end.</p><pre>With defaultProps, createElement time: 0.01123046875ms<br>Without defaultProps, createElement time: 0.003662109375ms</pre><p>That’s three times slower for that simple component and it contains only two defaultProps! <br>Just a quick disclosure, this doesn’t mean adding defaultProps will increase the render time by three, it just adds some milliseconds as it iterates over the defaults.</p><h4>Advantages and Disadvantages of ES6 Defaults:</h4><p>The main advantage default values has is that it’s a native syntax added in ES6 and supported in almost all browsers (except IE11) as a part of destructuring assignment.<br>In my opinion, the bigger problem with default values is that they create a difference between how we set default values in class components and how we set them in functional components, as setting a default value to a prop isn’t available in a class, the old class components will still have to use the old propTypes way, thus creating another difference between these two types of components. This problem will disappear in time since the use of class components should decline with hooks.</p><p>For the second problem we’ll have to change the Greet component a bit,<br>let’s change the component so it will accept a user object instead of firstName and lastName.</p><pre>const Greet = ({user = { firstName: &#39;John&#39;, lastName: &#39;Doe&#39; }}) =&gt; {<br>  return (&lt;div&gt;{`Hi ${user.firstName} ${user.lastName}`}&lt;/div&gt;)<br>}</pre><p>What’s the problem with the example we created? That’s right, <strong>immutability</strong>. The object we created as a default value will be recreated in every function call, so if we pass it down to a child component, the component will get a new reference every time and will cause a render on each parent render.<br>To fix that problem we will need to create the default value globally as a const so the reference won’t change:</p><pre>const defaultUser = { firstName: &#39;John&#39;, lastName: &#39;Doe&#39; };</pre><pre>const Greet = ({user = defaultUser}) =&gt; {<br>  return (&lt;div&gt;{`Hi ${user.firstName} ${user.lastName}`}&lt;/div&gt;)<br>}</pre><p>When using default values on latest browsers that don’t need to transpile destructuring assignment, it can even lead to a smaller bundle size. On the other hand, when using it in browsers that do need to transpile it, it may lead to a bigger bundle size since destructring assignment default values <a href="https://babeljs.io/repl#?babili=false&amp;browsers=&amp;build=&amp;builtIns=false&amp;spec=false&amp;loose=false&amp;code_lz=MYewdgzgLgBA4gJwKZNgXhgCgN4DMCWC0AcgIYC2SMGA5AFIgAWYNANDADakkVW0AiIJDQC-ASmoA-GNgBQMGMigBXBGCwAeACb4AbpOwADABL4YAEjyEelERexcbSEYZEBCDQHod-sbJFAA&amp;debug=false&amp;forceAllTransforms=false&amp;shippedProposals=false&amp;circleciRepo=&amp;evaluate=false&amp;fileSize=false&amp;timeTravel=false&amp;sourceType=module&amp;lineWrap=true&amp;presets=es2015%2Ces2016%2Ces2017%2Creact%2Cstage-0%2Cstage-1%2Cstage-2%2Cstage-3&amp;prettier=false&amp;targets=&amp;version=7.5.5&amp;externalPlugins=">transpiles</a> pretty weird.<br>I made a small example based on CRA with only prop-types and styled-components added. The example is made of 10 components, each one of them contains defaultProps. <br>Let’s take a look at a bundle size comparison after gzip:</p><p>Without defaultProps and transpile of default values: 55.969KB<br>Without defaultProps and not transpiling default values: 55.945KB<br>With defaultProps: 55.979KB</p><p>It looks like the difference to the bundle size is minimal.</p><h4>Summing it up:</h4><ul><li>React def. values lets us have a unified way of setting default values.</li><li>React def. values will be slower the more default values you set.</li><li>ES6 def. values may reduce your bundle size if deploying to browsers that already have destructuring assignment enabled.</li><li>When using ES6 def. values you have to remember the pitfalls and create non primitive values upfront so they won’t cause a render on child elements.</li><li>The React team decided on ES6 def. values as a way to set default values for functional components. A warning was already <a href="https://github.com/facebook/react/pull/16210">added</a> as a part of the process to deprecate defaultProps in functional components.</li></ul><p>It looks like we will see changes like what I talked about in the upcoming version of React, and it’s all a part of making React better for us the developers and for our users. The React team is working hard on tackling performance issues and changing the way we see the web now. <br>Keep up the great work React team ❤️</p><p>Hope I sold it well, but if you have any questions, feel free to ask.<br>I’m here and also on <a href="https://twitter.com/matanbobi">twitter</a>.<br>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=443c19d9e7f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>