<?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 Aditya Agarwal on Medium]]></title>
        <description><![CDATA[Stories by Aditya Agarwal on Medium]]></description>
        <link>https://medium.com/@adityaa803?source=rss-9c555799c00e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*XkazVdEAJc5t8QAZbTNjiA.jpeg</url>
            <title>Stories by Aditya Agarwal on Medium</title>
            <link>https://medium.com/@adityaa803?source=rss-9c555799c00e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 05:37:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@adityaa803/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[Bring app components to Storybook]]></title>
            <link>https://medium.com/storybookjs/bring-app-components-to-storybook-5b67c19d2a4d?source=rss-9c555799c00e------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b67c19d2a4d</guid>
            <category><![CDATA[features]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Aditya Agarwal]]></dc:creator>
            <pubDate>Thu, 14 Jan 2021 20:55:25 GMT</pubDate>
            <atom:updated>2021-01-19T07:48:06.092Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/670/0*SwFHc4jS1SsXMvW0" /></figure><h3><strong>Mock API requests in Storybook with MSW</strong></h3><h4><strong>How to mock API requests in </strong>app components</h4><p>Storybook is great for documenting presentational components. The <a href="https://storybook.js.org/blog/revamping-storybooks-addon-ecosystem/">huge ecosystem of addons</a> gives us awesome goodies like automated visual tests, responsive views, theme togglers, accessibility checks and so much more.</p><p>But applications have components that make API calls to fetch data. These “app components” can be as large as entire pages. Libraries like React Query &amp; Apollo have a useQuery hook which makes data fetching seem trivial. Once React Suspense becomes stable, even more components will have data fetching inside of them.</p><p><strong>I created the </strong><a href="https://www.npmjs.com/package/msw-storybook-addon"><strong>MSW addon</strong></a><strong> to simplify mocking API requests for stories.</strong> It doesn’t depend on any UI framework or data fetching library. Even GraphQL requests can be mocked. Now your app components can share the benefits of the Storybook ecosystem no matter what tech stack you use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uaPHIjbiuAQO5L-h" /><figcaption>Story with mocked API data</figcaption></figure><p>I would like to mention that the real magic behind my addon is an awesome tool called <a href="https://mswjs.io/">Mock Service Worker</a> (MSW). With MSW we can intercept requests on the network level and provide mocked data in the response. My addon brings MSW to its full potential in the Storybook environment.</p><h3>Benefits of writing stories for app components</h3><p>As an application grows, the responsibility of a component also increases. A single component can fetch data from multiple endpoints, apply various styles and render different UI based on feature flags, user’s country or the host device. In this situation, it’s important that all the behaviors of such components are documented and discoverable.</p><p>Storybook let us pass different props to a component in each story. With MSW addon each story can also provide the response of the APIs that are called in the component. This way we can document all the behaviors of a component and that has a huge payoff.</p><ol><li>We get to develop components in an isolated sandbox with mocked API calls.</li><li>We don’t need to wrangle with the database, switch feature flags or change A/B test buckets just to check how an unfamiliar part of our app behaves.</li><li>Component reuse is maximised. New teammates don’t have to ask if some UI is already built. They can just visit the storybook and see what components fit their needs.</li><li>With <a href="https://www.chromatic.com/">Chromatic</a>, we get automated visual snapshots for each story. If a bug in a component causes style breakage we’ll be notified in the PR.</li><li>We can reuse our mocks in both stories and behavioral tests since MSW itself supports Node.js. So we get a 2x benefit for the same effort.</li><li>Addons like <a href="https://www.npmjs.com/package/%40storybook%2Faddon-a11y">Accessibility</a> &amp; <a href="https://www.npmjs.com/package/storybook-mobile">Mobile UX</a> gives us hints on how to improve our app’s UI.</li><li>With <a href="https://www.npmjs.com/package/storybook-addon-designs">Figma addon</a> we can embed live mockups alongside the component story.</li></ol><p>The <a href="https://storybook.js.org/addons">Storybook catalog</a> is filled with useful addons like above so definitely check it out. Even better, make your own addons by following this <a href="https://www.chromatic.com/blog/how-to-build-a-storybook-addon/">tutorial</a>.</p><h3>Get Started with MSW addon</h3><p>First we need to install the following packages from npm.</p><pre>npm i -D msw msw-storybook-addon</pre><p>Then enable msw on our storybook by adding these lines in ./storybook/preview.js file.</p><pre>import { addDecorator } from ‘@storybook/react’;</pre><pre>import { initializeWorker, mswDecorator } from ‘msw-storybook-addon’;</pre><pre>initializeWorker();</pre><pre>addDecorator(mswDecorator);</pre><p>Since MSW uses a service worker to mock APIs we need to generate one in the same public folder that the app uses.</p><pre>npx msw init public/</pre><p>Then we can tell Storybook to also use the same public folder.</p><pre>npx start-storybook -s public -p 6006</pre><p>The location of the public folder depends on the tech stack. <a href="https://mswjs.io/docs/getting-started/integrate/browser">MSW guide</a> have a page dedicated to this.</p><p>The last step is to provide an array of mock handlers to the msw parameter of the relevant story like we do below. If you’re unfamiliar with MSW API check their <a href="https://mswjs.io/docs/getting-started/mocks/rest-api">guide</a>.</p><pre>import { rest } from &#39;msw&#39;;</pre><pre>export const SuccessBehavior = () =&gt; &lt;UserProfile /&gt;;</pre><pre>SuccessBehavior.story = {<br> parameters: {<br>   msw: [<br>     rest.get(&#39;/user&#39;, (req, res, ctx) =&gt; {<br>       return res(<br>         ctx.json({<br>           firstName: &#39;Neil&#39;,<br>           lastName: &#39;Maverick&#39;,<br>         }),<br>       );<br>     }),<br>   ]<br> },<br>};</pre><p>Now if your component makes an API call to <strong>/user</strong> the response will be the mocked one as seen below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9A3YgSxxpF2uOlgT" /><figcaption>Demo of mocked /user API</figcaption></figure><p>What’s cool is that our mocks work as it is with Fetch, XHR, Axios. Libraries like React Query, Apollo &amp; Urql also work with a tiny bit of setup code. Examples for each of them are present in the <a href="https://msw-sb.netlify.app/?path=/story/guides-introduction--page#demos">addon documentation</a>.</p><p>Also note that we can create multiple stories for a component and provide different responses in each story. That way we can document what UserProfile will render when API returns correct data, incorrect data or when it fails.</p><h3>Writing full page stories</h3><p>Since we are able to mock API requests in Storybook, it’s also possible to write stories for page components. Let me show how to do it with an example.</p><p>Consider an app which uses React Router to render a Film component at route /films/:filmId . The Film component uses the <strong>filmId</strong> param to fetch data for that film from <a href="https://swapi.dev/">Star Wars API</a> and show that film’s title.</p><p>The component will look like this.</p><pre>import { useParams } from &#39;react-router-dom&#39;;</pre><pre>export default function Film() {<br> const { filmId } = useParams();<br> const film = useFetchFilm(filmId);</pre><pre> return &lt;h1&gt;{film.title}&lt;/h1&gt;;<br>}</pre><p>If we visit <strong>/films/1</strong>, a request will go to <a href="https://swapi.dev/api/films/1"><strong>https://swapi.dev/api/films/1</strong></a> and “A New Hope” will be rendered as heading.</p><p>Let’s assume the stories for this page are in Film.stories.js. If in a story we simply render the Film component we’ll get two errors. First <strong>useParams</strong> hook will not work since the Film component is not rendered inside a <strong>Router</strong>. Second the API call will fail since there is no mock handler.</p><p>To make useParams hook work we wrap the Film component with MemoryRouter and provide it a route path. Then we tell React Router to render the Film component on that path.</p><pre>import { MemoryRouter as Router, Route } from &#39;react-router-dom&#39;;<br>import Film from &#39;./Film&#39;;</pre><pre>const MockTemplate = () =&gt; (<br> &lt;Router initialEntries={[&#39;/films/1&#39;]}&gt;<br>   &lt;Route exact path=&quot;/films/:filmId&quot;&gt;<br>     &lt;Film /&gt;<br>   &lt;/Route&gt;<br> &lt;/Router&gt;<br>);</pre><p>A great thing about Storybook is that we can reuse the template in each story and assign different mock handlers to each one. Let’s make our mock handler return the title “(Mocked) A New Hope” when a request comes for <a href="https://swapi.dev/api/films/1">https://swapi.dev/api/films/1</a>.</p><pre>import { rest } from &#39;msw&#39;;</pre><pre>const apiUrl = &#39;<a href="https://swapi.dev/api/films/1&#39;">https://swapi.dev/api/films/1&#39;;</a></pre><pre>export const NewHopeFilm = MockTemplate.bind({});</pre><pre>NewHopeFilm.story = {<br> parameters: {<br>   msw: [<br>     rest.get(apiUrl, (req, res, ctx) =&gt; {<br>       return res(<br>         ctx.json({<br>           title: &#39;(Mocked) A New Hope&#39;,<br>         }),<br>       );<br>     }),<br>   ],<br> },<br>};</pre><p>Here’s how it will look:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QrtpaoGwabYjO6SS" /></figure><p>This is all it takes to bring page components into Storybook. You’re not limited to just pages though. You can even write stories for entire subsections of your app. See this example of React Router + React Query app in the <a href="https://msw-sb.netlify.app/?path=/story/guides-introduction--page#render-pages-in-storybook">addon docs</a>.</p><h3>Final Thoughts</h3><p>Hope you find this addon useful. If you want to discuss more about it ask me on <a href="https://twitter.com/dev__adi">Twitter</a>. Here are some helpful links for you to check out.</p><ul><li><a href="https://msw-sb.netlify.app/">MSW Storybook</a></li><li><a href="https://github.com/itaditya/msw-storybook-addon/tree/master/packages/docs">MSW Storybook source</a></li><li><a href="https://github.com/itaditya/msw-storybook-addon/">GitHub repo</a> (please give it a star).</li><li><a href="https://www.npmjs.com/msw-storybook-addon">npm package</a></li></ul><h3>Get involved</h3><p>Check out the <a href="https://storybook.js.org/addons">Addon Catalog</a> for more addons or learn how to <a href="https://www.chromatic.com/blog/how-to-build-a-storybook-addon/">create an addon</a>. Check out Storybook on <a href="https://github.com/storybooks/storybook">GitHub</a> and join the <a href="https://discord.gg/AaVxNMD">Discord</a> chat.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fd42fc0%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fd42fc0%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/9875acdd1d756e7af50bf68488b92f2d/href">https://medium.com/media/9875acdd1d756e7af50bf68488b92f2d/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b67c19d2a4d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/storybookjs/bring-app-components-to-storybook-5b67c19d2a4d">Bring app components to Storybook</a> was originally published in <a href="https://medium.com/storybookjs">Storybook</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing a Redux Hooked App]]></title>
            <link>https://medium.com/bitsrc/testing-a-redux-hooked-app-a8e9d1609061?source=rss-9c555799c00e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8e9d1609061</guid>
            <category><![CDATA[react-testing-library]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Aditya Agarwal]]></dc:creator>
            <pubDate>Mon, 12 Oct 2020 19:44:20 GMT</pubDate>
            <atom:updated>2020-12-05T18:17:59.348Z</atom:updated>
            <content:encoded><![CDATA[<p>In the <a href="https://blog.bitsrc.io/how-to-hook-redux-in-a-react-app-e1de2f6fa094">last post</a>, we built <a href="https://bit.dev/itaditya/redux-hooked-app/redux-app">a food ordering app</a> where we integrated Redux hooks with React.</p><p>In this post, we’ll learn how to write integration tests for it using React Testing Library.</p><figure><a href="https://bit.dev/itaditya/redux-hooked-app/redux-app"><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fknMcwoWVH-L-k6G.png" /></a><figcaption><a href="https://bit.dev/itaditya/redux-hooked-app/redux-app">My redux-app</a> (shared on <a href="https://bit.dev/">Bit.dev</a>)</figcaption></figure><p>All the integration tests discussed are <a href="https://github.com/itaditya/redux-hooks-for-food-delivery/blob/master/src/App.test.js">available on GitHub</a>.</p><h3>Choose a testing strategy</h3><p>For testing UIs we have three options — End to End tests, Integration tests, Unit tests. So which strategy should we use? I like this ideology from Kent Dodds.</p><blockquote>The more your tests resemble the way your software is used, the more confidence they can give you.</blockquote><p>In an ideal world we would write everything as E2E tests since they resemble how people use our app the most. But in practice they are hard to setup and slow to run. So we keep <strong>E2E tests for critical user flows only</strong>. (We’ll learn E2E testing in my upcoming article)</p><p>For everything else the next best thing we can do is write integration tests. For that my library of choice is React Testing Library (aka RTL). Here’s an example —</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/133c65d9e54619209fcdf147220a55df/href">https://medium.com/media/133c65d9e54619209fcdf147220a55df/href</a></iframe><p>We first render our App component. Then toggle the Veg Only checkbox and at last check that the right food items are shown in the menu. <strong>By reading the above code could you even tell if our app uses React, Redux or Hooks?</strong> That’s what integration testing is all about. Let’s dig deeper on why this approach is better than doing unit testing with Enzyme’s shallow rendering.</p><h4>We abstract some logic of a component into a separate component.</h4><p>If we move some code from a component to a reusable child component, our Enzyme based tests will stop working.</p><p>However, integration tests don’t care about the internal details of a component. If we have written tests for a component, everything inside of it will be executed. So if some code is moved to a child component it doesn’t matter. Just like how it won’t matter to the users.</p><blockquote>When you refactor you shouldn’t need to update your tests. If that happens what confidence are the tests giving you?</blockquote><h4>We change the name of a child component’s prop</h4><p>Suppose a component uses a Button component inside. The Button component had an onClick prop which was called when the user pressed the button. If we use shallow rendering for our component tests then Button component’s internals won’t be rendered. That means if we simulate a click event nothing would happen. Instead, we need to manually call the Button’s onClick prop.</p><p>That’s fine for now but watch what happens when the Button component’s onClick prop is renamed to onPress prop. Our component’s tests will keep passing however the application will stop working for real users. This is not a problem when writing integration tests with React Testing Library.</p><h4>This is bad, right?</h4><p>With just two situations its clear that Shallow Rendering <strong>fails when it shouldn’t </strong>but <strong>passes when it absolutely should fail</strong>.</p><p>For these reasons, I’m convinced that the norm should be integration tests. However, just so there’s no confusion I’m adding these points.</p><ul><li>When rendering a deep child component is a headache it&#39;s fine if you mock it. Some mocking is fine compared to mocking everything by default.</li><li>Unit tests are great for situations like say you want to ensure that a utility function works for all kinds of input arguments.</li><li>Think of three types of tests as a layered sieve. E2E catches severe bugs, integration tests smaller bugs and unit tests catches micro-bugs.</li></ul><h3>Testing our Food Ordering App</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*306B1z3XJLN-PjgD" /><figcaption>Photo by <a href="https://unsplash.com/@askkell?utm_source=medium&amp;utm_medium=referral">Andy Kelly</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>We start by writing the tests for our top-most component which is the App component. Just like we rendered App inside index.js we’ll do the same in the tests. That means wrapping our App in Redux provider etc. Let’s take a look at our integration tests step by step.</p><h4>Test loading indicator</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af01bc1d2269760f82bbede7eeccc5b9/href">https://medium.com/media/af01bc1d2269760f82bbede7eeccc5b9/href</a></iframe><p>In this test starting from line 18, we want to ensure that while the app is loading, we show our app name and a loading indicator to the user. Its done through the following steps —</p><p><strong>i. We call the renderApp function.</strong></p><p>We’ve made a helper function called <strong>renderApp</strong>. It wraps the App component with a Redux provider and pass it a store instance. We also allow passing custom props to the App component. Inside our test we call renderApp. This will render our App component to JS DOM. After that we’ll be able to use <strong>screen</strong> to get stuff from the rendered DOM.</p><p>By passing the store this way, we ensure that each test gets its own store and doesn’t modify the store for next test. When we want to modify the store before rendering we can create one in the test itself and pass that to renderApp <a href="https://github.com/itaditya/redux-hooks-for-food-delivery/blob/master/src/Comps.test.js#L67">like this</a>.</p><p><strong>ii. We assert that Ordux heading is displayed.</strong></p><p>If you’re familiar with testing then you know that we use expect to check whether the received output matches the expected output.</p><p>We need to assert that our page heading has the text <strong>Ordux</strong>. So we need to extract the text content of heading. But even before that we need to be able to find the rendered heading DOM node. You might be surprised that <strong>we’re not using CSS classes, test id attributes or a component name</strong> to find the heading DOM node.</p><p>Instead, we’re using <strong>getByRole(‘heading’)</strong>. All h1 to h6 elements have the aria role of heading and this method uses <strong>roles</strong> to get the DOM nodes. Notice that it resembles how screen-reader users would find the heading.</p><p><strong>iii. We assert that Loading message is displayed.</strong></p><p>Previously we use the heading role for the assertion. In line 23, we’re using the role of <strong>status</strong>. But there is no &lt;status&gt; element in HTML so what’s happening?</p><p>Let’s look at what App component is doing —</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/39ca151034587244b83e0f115702faa0/href">https://medium.com/media/39ca151034587244b83e0f115702faa0/href</a></iframe><p><strong>useLoadFoodData</strong> tells App the current status of the API call. App then passes the status to Message component. When status prop is equal to <strong>loading</strong>, Message will render an <a href="https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Live_Regions">aria live region</a> with role as <strong>status</strong>. This way screen reader users would be informed when some content is updated via JS.</p><p>In a way, RTL forces us to step up our accessibility game. Had we just used a classname to query a DOM node we might have missed using an aria live region and screen reader users won’t know that loading is finished and that they can start interacting with the app.</p><p><strong>Note —</strong> In our test above, we are calling waitForElementToBeRemoved. That is for <a href="https://kentcdodds.com/blog/fix-the-not-wrapped-in-act-warning">fixing the act warning</a>. In short we’re telling React that the state update which leads to removing of loading indicator is intentional.</p><h4>Test for Veg Only checkbox</h4><p>In our app, users can click on the Veg Only checkbox and it will show them only vegetarian food items. Let’s see how we can test that flow.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d85bd2634eae7846e3f797a46f1294f/href">https://medium.com/media/0d85bd2634eae7846e3f797a46f1294f/href</a></iframe><p><strong>i. We mock the API call using jest.</strong></p><p>When we write integration tests we often mock API calls so that our CI testing pipeline stays simple and also run fast. It also enables us to simulate situations like API taking too long or giving the wrong response.</p><p>There are a couple of ways to mock our APIs. <a href="https://testing-library.com/docs/react-testing-library/example-intro#full-example">Kent Dodds prefers msw</a> but for this post we’ll just mock the <strong>loadFoodData utility</strong> so that it doesn’t make an API call. Inside the <strong>beforeEach</strong> we mock the implementation of loadFoodData so that a promise resolves with static data. Inside <strong>afterEach</strong> we restore the utility so that some other test could access the real loadFoodData utility if needed.</p><p>Next we render the App component and wait till the loading indicator is removed from DOM. When that happens we know that API is done loading and our menu would be visible.</p><p><strong>ii. Trigger click events.</strong></p><p>Now we need to turn on Veg Only checkbox. We find the checkbox DOM node using <strong>getByRole</strong>. If there are multiple checkbox, we can target a particular one by matching its <strong>name</strong>. We then click on the checkbox using <strong>fireEvent.click</strong>.</p><p><strong>iii. Test that enabling Veg Only filter hides items.</strong></p><p>After we click on the checkbox, out of the two food items we should only see the Veg one. To assert that, we need to get the DOM nodes for the two food items. Here we’ll use queryByText and getByText. Just like people find stuff by reading text, we find the DOM nodes using the text written in it.</p><p>But why do we need two separate methods? The reason is that getByText raises an error if it doesn’t find any matching DOM node. This is useful when we expected a DOM node to be present but its not there. Notice that we have used <strong>getByText</strong> along with <strong>toBeInTheDocument</strong>. However when we want to assert that a DOM node is not present then we use queryByText. It will not throw an error instead it will just return <strong>null</strong>.</p><p>From line 43 we test that when we disable the filter it starts showing the two items again. With that we’re done testing the entire Veg Only filter flow.</p><p>If you want to see an even bigger example of integration testing then check <a href="https://github.com/itaditya/redux-hooks-for-food-delivery/blob/master/src/App.test.js#L53">this test on GitHub</a>. It tests that when we add and remove items from cart, the right quantity is shown and the final price in the footer also updates.</p><h4>Testing Approach summarized</h4><p>The way I write tests can be summarized like this —</p><ul><li>I start with the top-most component App, render it as root and then test full user flows. Its not a problem if a test block becomes long.</li><li>I render the component inside each test instead of beforeEach because I might want to setup something in a test before rendering or pass additional props to the component when it mounts.</li><li>I target DOM nodes using their aria roles or text content since those are things that matter to user. The user clicks on the <strong>*button*</strong> with text <strong>*Submit*</strong>. They aren’t informed of the classes or ids on the button.</li><li>If there are edge cases not covered by the normal user flows then I write separate tests for those and generally they stay small.</li><li>Child components can do extra stuff which App doesn’t care about. Those can be tested in a <a href="https://github.com/itaditya/redux-hooks-for-food-delivery/blob/master/src/Comps.test.js">separate test where Child component is rendered</a> as root.</li></ul><h3>Conclusion</h3><p>In this article we learned how to pick a testing strategy, mock API calls and write integration tests for entire user flows. But there’s one more surprise.</p><p>Notice that only the rendering step required knowledge of React. The other steps didn’t care about implementation details. They just interacted with the DOM directly. Because of this reason Testing Library is able to support various UI frameworks. That means whatever you’ve learned in this article can be applied <a href="https://testing-library.com/docs/vue-testing-library/intro">when testing other framework apps</a>.</p><p>If you enjoyed the article, smash the clap button. It really motivates me. If you have any questions or if you want to stay up to date with latest tech <a href="https://twitter.com/dev__adi">follow me on Twitter</a>.</p><h3>Learn More</h3><ul><li><a href="https://blog.bitsrc.io/build-scalable-react-apps-by-sharing-uis-and-hooks-fa2491e48357">Build Scalable React Apps by Sharing UIs and Hooks</a></li><li><a href="https://blog.bitsrc.io/revolutionizing-micro-frontends-with-webpack-5-module-federation-and-bit-99ff81ceb0">Revolutionizing Micro Frontends with Webpack 5, Module Federation and Bit</a></li><li><a href="https://blog.bitsrc.io/building-a-react-component-design-system-8b643bb8922b">Building a React Design System</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8e9d1609061" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bitsrc/testing-a-redux-hooked-app-a8e9d1609061">Testing a Redux Hooked App</a> was originally published in <a href="https://medium.com/bitsrc">Bits and Pieces</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Hook Redux in a React App]]></title>
            <link>https://medium.com/bitsrc/how-to-hook-redux-in-a-react-app-e1de2f6fa094?source=rss-9c555799c00e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1de2f6fa094</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[redux]]></category>
            <dc:creator><![CDATA[Aditya Agarwal]]></dc:creator>
            <pubDate>Mon, 05 Oct 2020 22:30:30 GMT</pubDate>
            <atom:updated>2020-10-13T04:12:52.537Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RjllPBTCoxzeocyO4NZrQg.jpeg" /></figure><p>In this article, we’ll learn how to use the new Redux hooks to build a food ordering app. It’ll cover various UI patterns like fetching data from API, adding items to cart, and applying filters.</p><p>I’ve shared <a href="https://bit.dev/itaditya/redux-hooked-app/redux-app">my demo app</a> as a component, on <a href="https://bit.dev/">Bit.dev</a>. Feel free to test, inspect, and install it.</p><figure><a href="https://bit.dev/itaditya/redux-hooked-app/redux-app"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X_8kpGFyFbdSRomnqS8u0g.png" /></a><figcaption><a href="https://bit.dev/itaditya/redux-hooked-app/redux-app">My redux-app</a> (shared on <a href="https://bit.dev/">Bit.dev</a>)</figcaption></figure><h3>Application Overview</h3><p>Just like traditional SPAs, we show a loader till the API finishes and then we show the menu to the user. This is how this particular feature works in our React + Redux app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cfxzqve4DNPCd9-TQt24mQ.png" /><figcaption>Flow of API data in React-Redux app</figcaption></figure><p>If you are familiar with Redux then you’ll notice that the new thing with Redux hooks is that we don’t get store data from connect HOC. Instead we use the useSelector hook. Similarly we get dispatch from useDispatch hook.</p><p>This <a href="https://youtu.be/dpw9EHDh2bM?t=413">talk from Sophie and Dan</a> already covers when hooks are better than HOCs so I won’t gush about it too much. One side-benefit I feel is that now only parent sends data in props. All other data comes from hooks so its easier to find the root cause of a bug.</p><h3></h3><p>One unsaid benefit of hooks is they clearly communicate where the data is coming from. With HOCs all kinds of data would be passed as props. So you&#39;re left hunting through codebase did this prop come from parent / redux / some other hoc pic.twitter.com/pXdu7XVZiO</p><p>Now let’s take a look at the code. Our app has two main files- <strong>redux.js</strong> and <strong>App.js</strong> which we’ll cover in detail. However there are some UI components present in <strong>Comps.js</strong> file to make this app work which we’ll peek through in the next article.</p><p>You can check all the <a href="https://github.com/itaditya/redux-hooks-for-food-delivery">code for this app on GitHub</a>.</p><h3>redux.js file</h3><p>This file contains the ACTIONS mapping, the foodReducer and the Redux store creator. If you only care about how to use the new Redux hooks then skip this section and go to the next section where we discuss App.js file.</p><h4>Actions mapping</h4><p>By having an object called <strong>ACTIONS</strong> we get to quickly know what all actions are possible and it also helps with auto-completing action types.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a086b8c49bf3690677ec58b204ebdbfa/href">https://medium.com/media/a086b8c49bf3690677ec58b204ebdbfa/href</a></iframe><h4>Food Reducer</h4><p>As you must have heard a million times the job of a reducer is to return a new state based on the type of dispatched action.</p><p>We assign an initial state to foodReducer which looks like this-</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f71c3b2e1d0667ce2cbbfde756211aa4/href">https://medium.com/media/f71c3b2e1d0667ce2cbbfde756211aa4/href</a></iframe><p>Before we proceed further let’s look at our foodReducer in action in this video.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F459846321%3Fapp_id%3D122963&amp;dntp=1&amp;display_name=Vimeo&amp;url=https%3A%2F%2Fvimeo.com%2F459846321&amp;image=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F960697501_1280.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=vimeo" width="1920" height="904" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a636f872822425f2c185dc1db99cae7/href">https://medium.com/media/6a636f872822425f2c185dc1db99cae7/href</a></iframe><p>You’ll notice that the actual data about each food item is stored by its id in the <strong>menuById</strong> key of the store. The <strong>menuIdList</strong> array only contains a list of ids per diet. There are three main benefits of storing data this way-</p><ol><li><strong>Reduce duplicate copies —</strong> If we had stored data directly in arrays then some food items would be duplicated in both <strong>all</strong> type and <strong>veg</strong> type.</li><li><strong>Faster item access —</strong> Since we’re storing stuff by id, if we know the id accessing it will happen in O(1) instead of digging through an array which in best case scenario is O(log n).</li><li><strong>Filter results get cached —</strong> Suppose we get the items for a diet via an API call. We can cache the food item ids per diet so that when user selects a diet again we can pick the ids from cache instead of making an API call.</li></ol><p>This technique is called <a href="https://redux.js.org/recipes/structuring-reducers/normalizing-state-shape#normalizing-state-shape">normalization</a>.</p><p>Similar to this<strong> cartByIds</strong> only store a mapping of item id and its quantity. The only downside is that we can’t just directly show data of store to user we’ll need to do some pre-processing to mold the data into the shape the various views requires. We’ll cover this when we talk about selectors.</p><p>Now let’s write the logic for <strong>CHANGE_DIET action</strong> in the reducer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0bdc4be256fc255c8da191cdf108f35/href">https://medium.com/media/a0bdc4be256fc255c8da191cdf108f35/href</a></iframe><p>Here we get the current value of diet from the store and then return a new state which has only two differences- The diet value is opposite of the previous one and the cartByIds is empty.</p><p>Notice that our reducer contains the actual toggling logic and is not treated as a dumb layer just to store whatever data comes in action payload.</p><p>Next, we have to deal with <strong>LOAD_MENU action</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ad14bba3518d31276e3e1cbbf2efb5e/href">https://medium.com/media/6ad14bba3518d31276e3e1cbbf2efb5e/href</a></iframe><p>When LOAD_MENU is dispatched, it’ll send an array of food items in the menu key of payload. We put this array into our store like this-</p><ol><li>Traverse the menu array and store each item by id in menuById object.</li><li>Make an array of ids for all items.</li><li>Make an array of ids for only veg items.</li><li>Return the new state with changes in menuById and menuIdList.</li></ol><p>Similarly, we have <a href="https://github.com/itaditya/redux-hooks-for-food-delivery/blob/master/src/redux.js#L51">implemented ADD_TO_CART and REMOVE_FROM_CART</a>. We store data (quantity etc.) for each item by its id inside <strong>cartByIds</strong>. When user adds an item to cart, the dispatched action gets that item’s id in payload. Then we find the item’s quantity in cartByIds, change it by 1 and again store it.</p><h4>Redux Store</h4><p>We make a function in which we create a Redux store, pass the foodReducer to it. We also enable the Redux DevTools extension for better debugging and then export this function.</p><p>Then in index.js, we create a store, wrap the App component inside Provider component from react-redux package and pass the store as a prop to the Provider.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ec084c2a4f8f1b2eb08d6e43b15e2cd/href">https://medium.com/media/7ec084c2a4f8f1b2eb08d6e43b15e2cd/href</a></iframe><h3>App.js file</h3><p>The App.js file is our top most parent component React renders. The whole file is doing the following stuff —</p><ol><li>Read the diet from store and update it when user toggles the Veg Only checkbox.</li><li>Triggers an API call to load the menu.</li><li>Pass the API status to Message component so user is notified when API is done loading.</li><li>Get the loaded menu from Redux store and pass it to MenuList component.</li><li>Render PaymentFooter component.</li></ol><p>Let’s look at how some of these things are done —</p><h4>Diet Toggler</h4><p>If user clicks on the <strong>Veg Only</strong> checkbox then we need to only show the vegetarian items. So we need a way to get the diet value from the store and also update it.</p><p>To get data from Redux store, we use the <strong>useSelector</strong> hook from the react-redux package. The useSelector hook takes a function (selector). This function gets the entire Redux store state as a parameter and its job is to return only the state needed. For this case we only need the diet state.</p><p>We get the dispatch function from <strong>useDispatch</strong> hook and we dispatch an action of type <strong>CHANGE_DIET </strong>from the <strong>handleVegToggle </strong>event handler. At last we plug the diet value and the handleVegToggle event handler into the checkbox.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b194a82479462ed9743b919283fec318/href">https://medium.com/media/b194a82479462ed9743b919283fec318/href</a></iframe><h4>API Loader</h4><p>All of the API loading logic is abstracted away into the <strong>useLoadFoodData</strong> hook. It does two things-</p><ol><li>Track the API loading status in a React state named <strong>stateAPIStatus</strong> and return it so App component knows about it.</li><li>When API call finishes, dispatch the <strong>LOAD_MENU</strong> action to store the API data in Redux store.</li></ol><p>The code is pretty self-explanatory.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0190d25d95eda38a9af74d85462d442c/href">https://medium.com/media/0190d25d95eda38a9af74d85462d442c/href</a></iframe><p>The App component uses the hook like so</p><pre>const stateAPIStatus = useLoadFoodData();</pre><p>We pass <strong>stateAPIStatus</strong> to Message component which will render an aria live region to notify user when API data is being fetched or if it errors.</p><h4>Display Menu</h4><p>As we previously saw, useLoadFoodData hook takes care of updating the store with the menu data from API. So now App component can get the menu from store using a selector and pass the data to the MenuList component as a prop.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/caa57bab3ffbce2534d7e194d6af3a61/href">https://medium.com/media/caa57bab3ffbce2534d7e194d6af3a61/href</a></iframe><p>But you’ll notice that to get diet and menuList we’re using two useSelector and both usage are slightly different. This raises three questions.</p><ol><li>Why are we using a separate selectorMenu instead of inline function?</li><li>Why are we passing shallowEqual function as a second argument to useSelector.</li><li>Why do we need two separate useSelectors in the first place?</li></ol><p>The first question has a simple answer, since we stored data in Redux store by id we need to do some simple pre-processing in the selector to return the array of food items with complete details. It is more readable if we keep it in a function outside the component and this way we can also re-use the selector in other components.</p><p>We would also need to do this if we were using memoized selectors with something like reselect. More details in the <a href="https://react-redux.js.org/api/hooks#using-memoizing-selectors">docs</a>.</p><p>To answer the next two questions we’ll need to understand selectors in-depth.</p><h3>Redux Selectors</h3><p>The function that we pass to useSelector hook as first argument is called a selector. The selectors are run whenever any value in the Redux store changes. But to improve performance Redux does one optimization. It does a referential equality check between the old and new value returned by the selector.</p><p>In our diet selector, it was just returning a string. When the store updates, the diet selector runs and then useSelector does this comparison</p><pre>const oldDietVal = getOldVal();<br>const newDietVal = selectorMenu(storeState);</pre><pre>newDietVal === oldDietVal</pre><p>If by referential equality, both values are same then useSelector just returns the old value.</p><p>Now let’s look at our selectorMenu selector function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d9080d793975f3f6b2bcc885e47c4e65/href">https://medium.com/media/d9080d793975f3f6b2bcc885e47c4e65/href</a></iframe><p>First we create a <strong>fresh new menuList</strong> array. Then we find all the ids for the user’s currently selected diet and then populate menuList<strong> </strong>with the data of each id. At last we return the menuList array.</p><p>But here’s the thing, as we saw Redux only does a referential equality check between the old and new value and in JavaScript.</p><pre>[] === [] // is always false</pre><p>That means useSelector will always return the new array. It’s a problem because when we use the returned menuList array in a useEffect or pass it to MenuList child component, React will notice that the array is different from last time and will always update.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*SO8EnvXoeVKChaBQeZXo9Q.gif" /><figcaption>Unoptimized selector usage</figcaption></figure><p>Above you’ll notice that when user toggles the Veg Only checkbox then the menuList changes so effect runs like expected <strong>but when user adds an item to the cart then there is no perceived change in menuList but still the effect runs and we want to avoid this.</strong></p><p>To avoid this performance penalty we can pass a custom comparison function as the second argument to useSelector. In our case we provide the<strong> shallowEqual</strong> function (from react-redux package). Now useSelector will do a shallow comparison instead of referential equality between the new and old value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*yrpMToj0MviV159hjQIzPg.gif" /><figcaption>Optimized selector usage via shallowEqual</figcaption></figure><p>Notice that in the above example, React only triggers updates when user clicks on Veg Only but doesn’t do anything when user adds an item to the cart.</p><p>If you understood this then you’d also figure out why we used two useSelector and not return a big object through one useSelector. This kind of selector would have to return an object like this</p><pre>{<br>  diet: &#39;veg&#39;,<br>  menuList: [],<br>}</pre><p>Since it always returns a new object which also has a newly created menuList array the shallow comparison check will start failing again. To solve this we might provide a deep comparison as the second argument to useSelector but that can be an expensive operation. So its a good idea to just stick with separate selectors for individual states.</p><blockquote>Just like we moved away from one componentDidMount to independent useEffects, we need to move away from one mapStateToProps to multiple useSelectors.</blockquote><h3>Conclusion</h3><p>In the reducer we went through two actions CHANGE_DIET, LOAD_MENU. We dispatched them from components, custom hooks and at last learned how to get data from store using selectors.</p><p>The code for integrating UI components with Redux can be found in this <a href="https://github.com/itaditya/redux-hooks-for-food-delivery/blob/master/src/Comps.js#L102">Comps.js file on GitHub</a>. In the same file you’ll see how we display the total price in PaymentFooter component.</p><p>In the next article, we’ll <a href="https://blog.bitsrc.io/testing-a-redux-hooked-app-a8e9d1609061">learn how to write integration tests with React Testing Library</a> for our hooked React-Redux app. <a href="https://twitter.com/dev__adi">Follow me on Twitter</a> if you want to get notified about it. If you like this article then smash the Clap button, it helps me stay motivated.</p><h3>Learn More</h3><ul><li><a href="https://blog.bitsrc.io/build-scalable-react-apps-by-sharing-uis-and-hooks-fa2491e48357">Build Scalable React Apps by Sharing UIs and Hooks</a></li><li><a href="https://blog.bitsrc.io/11-useful-custom-react-hooks-for-your-next-app-c66307cf0f0c">11 Useful Custom React Hooks for Your Next Web App</a></li><li><a href="https://blog.bitsrc.io/10-useful-react-components-for-2020-35fd6af56909">10 Useful React Components for 2020</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1de2f6fa094" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bitsrc/how-to-hook-redux-in-a-react-app-e1de2f6fa094">How to Hook Redux in a React App</a> was originally published in <a href="https://medium.com/bitsrc">Bits and Pieces</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Javascript: Why Named Arguments are Better than Positional Arguments]]></title>
            <link>https://medium.com/bitsrc/javascript-why-named-arguments-are-better-than-positional-arguments-9b15ab3155ef?source=rss-9c555799c00e------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b15ab3155ef</guid>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Aditya Agarwal]]></dc:creator>
            <pubDate>Thu, 06 Aug 2020 16:30:43 GMT</pubDate>
            <atom:updated>2020-08-11T14:06:59.455Z</atom:updated>
            <content:encoded><![CDATA[<h3>JavaScript: Why Named Arguments are Better than Positional Arguments</h3><p>By passing arguments as objects, we can decrease bugs in our app. That’s always an important thing but even more so when sharing reusable functions/components between apps (for example, using tools like <a href="https://bit.dev/frontend-teams">Bit</a>).</p><p>This approach is called named arguments. Read the full article to understand why its better.</p><figure><a href="https://bit.dev/digiaonline/react-foundation/switch"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-RGwbautWHbtJRCQ9SRlsQ.png" /></a><figcaption>Example: A <a href="https://bit.dev/digiaonline/react-foundation/switch">React component</a> shared on <a href="https://bit.dev/">Bit</a> (<a href="https://github.com/teambit/bit">Github</a>)</figcaption></figure><p>Before talking about named arguments let’s first clearly understand positional arguments and the problems they can cause.</p><h3>What are positional arguments?</h3><p>You must be pretty familiar with positional arguments even if you heard the name for the first time.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cecdbab8a5c44fbb19ac76956cd8b7c9/href">https://medium.com/media/cecdbab8a5c44fbb19ac76956cd8b7c9/href</a></iframe><p>The greet function takes two arguments- firstName &amp; lastName. The caller has to make sure that the firstName is the first argument and the lastName is the second argument. The important takeaway here is that the <strong>name of the argument doesn’t have any significance</strong>. The only thing that matters is <strong>the order in which the arguments are passed</strong>.</p><p>This familiar approach is called positional arguments. It is usually fine for cases where you pass one or two arguments since its hard to mess up the order of arguments. But if you have to call a util which takes 6 arguments it would be hard to remember the order of arguments to pass. You don’t want to pass the password in place of the username argument.</p><h3>Problems with Positional Arguments</h3><p>Positional Arguments are pretty straight-forward to do but you will face some challenges with them.</p><h4>1. Can’t skip middle arguments</h4><p>Say you have changed the greet function from earlier such that it takes 3 arguments now — firstName, middleName, lastName. Since many people don’t have a middle name you want to make middleName an optional argument. The only way to call greet function with only firstName and lastName is this.</p><pre>greet(&#39;Aditya&#39;, null, &#39;Agarwal&#39;);<br>// Correct ✅</pre><pre>greet(&#39;Aditya&#39;, &#39;Agarwal&#39;);<br>// Incorrect ❌</pre><p>You can’t just provide firstName and lastName. This problem becomes more pronounced when the number of optional arguments increases to let’s say 5. Now you have to provide 5 nulls just to be able to provide arguments after those.</p><h4>2. Adding types to positional arguments is less cleaner</h4><p>Nowadays adding types to your utilities is becoming very common. With positional arguments you have no choice but to inline the types along with the function definition. This can obfuscate the code a little. It would be much better if we could declare type definitions of all arguments in one block.</p><p>I don’t want to cover Types in this article. You can bug my friend <a href="https://medium.com/@gurjitmehta">Gurjit</a> to cover this in his articles as he’s the one who pointed this out to me.</p><p><a href="https://medium.com/@gurjitmehta">Gurjit Singh - Medium</a></p><h4>3. Cause subtle bugs</h4><p>Positional Arguments pack a lot of implicit behavior which can be the cause of subtle bugs. Let&#39;s see a common JS trick question</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/33cc575ad1f8462e7a781ca4b03b4b4e/href">https://medium.com/media/33cc575ad1f8462e7a781ca4b03b4b4e/href</a></iframe><p>Surprised? The reason for this weird output is hidden behind the implicit nature of positional arguments. You see the map and parseInt functions are hiding some of their secrets in plain sight.</p><p>Let’s review the code numbers.map(parseInt) again.</p><p>What exactly is happening here?</p><ul><li>We run the map function on the numbers array.</li><li>map takes the first item of the array and passes it to parseInt.</li><li>Now, for the first item in the array (i.e. 1) it would do parseInt(1). Right...? <strong>Wrong!!!</strong></li></ul><p>Actually map passes three arguments to its callback function. The first is the current item in the array, the second is the index of the item. The third is the entire array. This in itself has no problem but the real issue is with the latter part.</p><p>numbers.map(parseInt) is not the same as numbers.map((item) =&gt; parseInt(item)). You could make the assumption that since the callback function just takes the item argument and pass it to parseInt we can skip the additional step. But the two are different: in the former, we pass all the data from map to parseInt whereas in the latter we only pass the item.</p><p>You might not know but there is a second argument of parseInt called the radix. By default, the value of radix is 10 (base 10 because we humans follow the decimal system for counting). What went wrong with the code was that we passed the <strong>index of the current item as the radix value to parseInt</strong>. These are the actual function calls that happened-</p><pre>parseInt(&#39;1&#39;, 0, [...]);</pre><pre>parseInt(&#39;4&#39;, 1, [...]);</pre><pre>parseInt(&#39;8&#39;, 2, [...]);</pre><pre>parseInt(&#39;10&#39;, 3, [...]);</pre><p>Now that we know the issues, how can we do better?</p><h3>Alternative to Positional Arguments</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2PGPTSwUORxwjRwNKrH56w.jpeg" /></figure><p>What if a function could tell by the name, what arguments it expects? That way even if you pass extra data to it by mistake it will only use the things it needs.</p><p>Let’s make our own wrapper over parseInt. Here’s a naive implementation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/26421e0939394b3bdafe05c4559da60e/href">https://medium.com/media/26421e0939394b3bdafe05c4559da60e/href</a></iframe><p>myCustomParseInt accepts only one argument and that is an object. This object can have two keys– item &amp; radix. Let’s use our custom util with map. It will be necessary to have an intermediate step to send args received by callback to myCustomParseInt.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0436868602fadabe4ebf020f82b84506/href">https://medium.com/media/0436868602fadabe4ebf020f82b84506/href</a></iframe><p>Notice that even if we pass the index to myCustomParseInt it won’t cause any problems. That’s because myCustomParseInt will just ignore it. This pattern of passing objects to functions is called <strong>named arguments</strong>. It is lot more explicit than positional arguments.</p><p>To change the radix we have to explicitly pass the radix key. That means if we want to parse a string with base 2 we have to go to the docs and see the exact name of parameter (radix). If we blindly pass any other key it won’t do anything. This is great for us because it avoids unintended behavior.</p><h4>Named arguments with destructuring</h4><p>A while back JavaScript got a feature called destructuring. Let’s use this in myCustomParseInt implementation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63f7329c8a110f55cb56cbbb39a0c3e4/href">https://medium.com/media/63f7329c8a110f55cb56cbbb39a0c3e4/href</a></iframe><p>You’ll notice that just by adding two curly braces we get the benefits of named args but the ergonomics of positional args. You can think of destructuring as performing const item = objArgs.item;</p><p>If myCustomParseInt is called with <strong>undefined</strong> then JS would throw an error. That’s because undefined.item is not allowed. To avoid it we can add = {} in the end of destructuring. That way when we pass undefined it will now do {}.item which is valid JS. Here&#39;s the final implementation-</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1aa7e0789ff51e15c40e91a83b6d319b/href">https://medium.com/media/1aa7e0789ff51e15c40e91a83b6d319b/href</a></iframe><p>With named arguments pattern we can also skip the arguments we don’t want to provide since the function no longer depends on the order in which the arguments are passed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eeae11ae44e9d686193b2ce46d1cdb02/href">https://medium.com/media/eeae11ae44e9d686193b2ce46d1cdb02/href</a></iframe><p>In conclusion I’d say named arguments is a powerful pattern and it has become very commonplace nowadays but you don’t always need to use them. Sometimes you could even combine the two. The fetch API in browser is used like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8e6052184072061048fd7ad8eea1df2/href">https://medium.com/media/d8e6052184072061048fd7ad8eea1df2/href</a></iframe><p>Here the mandatory argument (API path) is a positional argument and then the optional params are accepted through named arguments.</p><p>Follow me on <a href="https://twitter.com/dev__adi">Twitter (https://twitter.com/dev__adi)</a> if you have questions or if you want to stay up-to-date with cool developer tips and interesting technologies.</p><h3>Learn More</h3><ul><li><a href="https://blog.bitsrc.io/3-ways-to-build-your-own-react-component-library-b4d00013a716">3 Ways to Build Your Own React Component Library</a></li><li><a href="https://blog.bitsrc.io/features-of-javascript-you-probably-never-used-4c117ba3f025">11+ JavaScript Features You’ve Probably Never Used</a></li><li><a href="https://blog.bitsrc.io/react-typescript-cheetsheet-2b6fa2cecfe2">React TypeScript: Basics and Best Practices</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b15ab3155ef" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bitsrc/javascript-why-named-arguments-are-better-than-positional-arguments-9b15ab3155ef">Javascript: Why Named Arguments are Better than Positional Arguments</a> was originally published in <a href="https://medium.com/bitsrc">Bits and Pieces</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Systems: React Buttons with the Base + Variant Pattern]]></title>
            <link>https://medium.com/bitsrc/design-systems-react-buttons-with-the-base-variant-pattern-c56a3b394aaf?source=rss-9c555799c00e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c56a3b394aaf</guid>
            <category><![CDATA[design]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[user-experience]]></category>
            <dc:creator><![CDATA[Aditya Agarwal]]></dc:creator>
            <pubDate>Mon, 20 Jul 2020 20:28:44 GMT</pubDate>
            <atom:updated>2020-07-20T20:28:44.784Z</atom:updated>
            <content:encoded><![CDATA[<h4>Composing React buttons for design systems with the Base and Variant pattern.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hsesml8-ctY003XDaJ2JFw.jpeg" /></figure><p>Design Systems are made to make the designs consistent across products. But they shouldn’t become a bottleneck for creativity. Some room for experimentation should be present. Let’s see how we can tread this fine line between flexibility and consistency using the base + variant pattern.</p><p>Suppose there’s a e-commerce platform with multiple products like the main shopping site, inventory management portal, email system. All of these are customer-facing software so they should reflect a common design language.</p><p>For that <strong>Sarah </strong>will be working on the design system and <strong>Ana</strong> will be using it in the main shopping site where people buy various products. Sarah figures out that the first priority is to have buttons inside the design system.</p><p>The buttons should be flexible enough to fit various product needs but not so much that we risk losing design consistency. When new product requirements come these buttons should be extendable too. If any of these elements are missing then the design systems adaption and impact will be negatively affected.</p><p>To accommodate all these requirements Sarah uses the Base + Variant pattern to build the buttons.</p><p>I’ve used <a href="https://bit.dev/"><strong>Bit</strong></a> (<a href="https://github.com/teambit/bit">Github</a>) to publish the base button and its variants, to my <a href="https://bit.dev/itaditya/tailwind-buttons">shared Bit component collection</a>.</p><figure><a href="https://bit.dev/itaditya/tailwind-buttons"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gHuGn4xB2K4lGcHw7Yr6mg.png" /></a><figcaption>My buttons published to a shared collection on <a href="https://bit.dev/">Bit.dev</a> — <a href="https://bit.dev/itaditya/tailwind-buttons">https://bit.dev/itaditya/tailwind-buttons</a></figcaption></figure><p>Each component is published as an independent package. That means each <em>component can be installed as an independent package</em>. No need to install an entire library with button variants that are irrelevant to you own project.</p><p>That also means each component will only be affected by changes to components it is dependent on. Unlike a library, changes are not global. When you maintain or install a component, <em>you only get updates that are relevant to that specific component</em>.</p><figure><a href="https://bit.dev/itaditya/tailwind-buttons/button-solid"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zqDAgGspvENg8ha2G1ZcIQ.png" /></a><figcaption>The button-solid component, published on <a href="https://bit.dev/">Bit.dev </a>— <a href="https://bit.dev/itaditya/tailwind-buttons/button-solid">https://bit.dev/itaditya/tailwind-buttons/button-solid</a></figcaption></figure><p>To learn more about it, read here:</p><p><a href="https://blog.bitsrc.io/how-to-publish-react-components-d04e0a7e33b9">How to Publish React Components</a></p><h3>Base + Variant Pattern</h3><p>In the base + variant pattern the core parts of a component that are <strong>not subject to change</strong> are isolated from the parts that are <strong>open to customization</strong>.</p><p>Things like core behavior are implemented inside the Base component. The Base is private i.e. it’s not meant to be used <strong>directly</strong> in the application. For each use case, a separate component (Variant) can be built on top of this Base component.</p><p>There is a great talk on this by the AirBnB design system team. Check it out once you’re done with this article.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FfHQ1WSx41CA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DfHQ1WSx41CA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FfHQ1WSx41CA%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/e71da880e2466f233a38b6dee5b77120/href">https://medium.com/media/e71da880e2466f233a38b6dee5b77120/href</a></iframe><p>Sarah has categorized the buttons into 3 types —</p><ul><li><strong>Solid buttons</strong> can have 3 variants (primary, danger &amp; plain) &amp; 3 sizes (base, large, small) and icons before and after the button text.</li><li><strong>Ghost buttons</strong> can have 2 variants (primary &amp; danger) &amp; 3 sizes (base, large, small) and icons before and after the button text.</li><li><strong>Icon buttons</strong> don’t have variants for now. Only size customization is supported. A single icon in the center is shown along with a tooltip.</li></ul><p>Since Solid button &amp; Ghost buttons have similar structure and core behavior Sarah will make a ButtonBase component first. Then the ButtonSolid &amp; ButtonGhost component can use ButtonBase internally.</p><p>Here’s some skeleton code to make these components. The example is in React here but the same concepts can be applied across libraries.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43bcca16db70a84d1d8f3e1f5b8861ac/href">https://medium.com/media/43bcca16db70a84d1d8f3e1f5b8861ac/href</a></iframe><p>As you can see IconButton is not using ButtonBase since there is almost nothing common between them. We could make a IconButtonBase and use it in IconButton but it would be an overkill at this point. If need does arise in future then the common parts can be moved from IconButton to IconButtonBase. IconButton will use IconButtonBase and no changes in the product side would be needed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WboQleHkxIDQdhKhh893WA.png" /><figcaption>Possible buttons with our implementation</figcaption></figure><p>You can clearly see how many usecases we can address with our implementation. Let’s check how Ana can use them in her product.</p><h4>Practical Usage</h4><p>The different type, variant, size of buttons are used to communicate different things to the users. Let’s take the following use cases for buttons as an exercise.</p><ol><li>Add to Cart button — Since most users buy multiple items together their main action is to add an item to cart. To make this button the most prominent on the product detail page Ana chooses a<strong> Solid button</strong> with <strong>primary variant</strong>.</li><li>Buy Now button — This is the second most useful interaction for users. As this is also present on product detail page Sarah recommends to not use the Solid button of primary variant. So instead Ana chooses a <strong>Ghost button</strong> with <strong>primary variant. </strong>It’s primary because it’s also a positive action.</li><li>Add to Wishlist button. — This can be useful for customers who just want to bookmark an item to buy later. Ana uses a <strong>large IconButton</strong> here.</li><li>Empty Cart button — User can empty the entire cart by clicking on this button. User needs to be slightly aware of buttons which destroy something or delete things. Ana chooses a <strong>Ghost button</strong> with <strong>danger variant </strong>for this.</li><li>Cancel Order button — User can cancel their entire order by clicking this button. This action will cost money to the company too. So the user should take extra precaution when using this button. To stress this Ana makes this a <strong>Solid button</strong> with <strong>danger variant</strong>.</li><li>Cancel Confirmation dialog — After user clicks on the Cancel Order button a confirmation dialog is shown. There will be two buttons side by side. As the Confirm button will cancel the order it’s a <strong>Solid button</strong> with <strong>danger variant</strong>. The Cancel button is neutral as it’s neither a positive action like buying an item nor a negative action like deleting stuff so it’s a <strong>Solid button</strong> with <strong>plain variant</strong>.</li></ol><h3>Composing Custom Buttons</h3><p>Suppose Ana has to make a banner for a new super special feature. The banner has a colorful CTA which is meant to gain user attention immediately. None of the existing button variants satisfy the needs of this special CTA.</p><p>One approach is that Ana could ask Sarah to make changes in design system components to support this variant. This can lead to many problems. Sarah will need to take care of one more variant which means testing it across products on every release. It also increases the API surface of existing components which can complicate the implementation of the component.</p><h4>Recommended Approach</h4><p>The biggest advantage of Base + Variant pattern is that it makes your design system super extendable. In this scenario Ana can make a component let’s say ButtonCustom for her product on top of ButtonBase. This has a couple of advantages —</p><ol><li>Since ButtonCustom is part of the product code instead of design system there is no extra maintenance cost on design system team.</li><li>ButtonCustom will be built on top of ButtonBase so it is ensured that there is some consistency and best practices baked in.</li><li>There will be a lot of room for customization in ButtonCustom. This gives Ana an opportunity to go all out with the new variant’s designs without complicating the design system.</li><li>If ButtonCustom breaks it will not affect other buttons in any way. So the issue will be isolated to only one component of only one product.</li></ol><p>So we can see that the Base Variant pattern provides us with a lot of design consistency meanwhile being flexible enough to support new variants for future cases.</p><p>I’ve built some buttons on this pattern using ReactJS and TailwindCSS. Check it out on Bit’s Playground.</p><p><a href="https://bit.dev/itaditya/tailwind-buttons">tailwind-buttons by itaditya · Bit</a></p><p>The full source code is available on <a href="https://github.com/itaditya/tailwind-buttons-for-design-system/tree/bit-separate">GitHub</a>.</p><p>If you like this article smash the clap button and share it with your friends. You can <a href="https://devadi.netlify.app/blog/async-await-hell">read more such articles on my blog</a>.</p><p><a href="https://devadi.netlify.app/blog/async-await-hell">How to escape from the async/await hell</a></p><p>Follow me on <a href="https://twitter.com/dev__adi">Twitter (https://twitter.com/dev__adi)</a> if you have questions or if you want to stay up-to-date with cool developer tips and interesting technologies.</p><h3></h3><p></p><h3>Learn More</h3><ul><li><a href="https://blog.bitsrc.io/how-to-publish-react-components-d04e0a7e33b9">How to Publish React Components</a></li><li><a href="https://blog.bitsrc.io/14-javascript-code-optimization-tips-for-front-end-developers-a44763d3a0da">14 JavaScript Code Optimization Tips for Front-End Developers</a></li><li><a href="https://blog.bitsrc.io/theming-react-components-with-css-variables-ee52d1bb3d90">Theming React Components with CSS Variables</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c56a3b394aaf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bitsrc/design-systems-react-buttons-with-the-base-variant-pattern-c56a3b394aaf">Design Systems: React Buttons with the Base + Variant Pattern</a> was originally published in <a href="https://medium.com/bitsrc">Bits and Pieces</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimize Your React App with React.memo]]></title>
            <link>https://medium.com/bitsrc/optimize-your-react-app-with-react-memo-ec52447b09ba?source=rss-9c555799c00e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec52447b09ba</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[optimize]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[memoization]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Aditya Agarwal]]></dc:creator>
            <pubDate>Thu, 18 Jun 2020 21:15:23 GMT</pubDate>
            <atom:updated>2020-06-19T08:20:53.616Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how to use <strong>React.memo</strong> and <strong>useMemo</strong> together to optimize your React app performance.</h4><figure><img alt="Person running faster than others" src="https://cdn-images-1.medium.com/max/1024/0*wGujXKr08R9cktEl" /><figcaption>Photo by <a href="https://unsplash.com/@slelham?utm_source=medium&amp;utm_medium=referral">Steven Lelham</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>“Memoization is an optimization technique used to primarily speed up programs by storing the results of expensive function calls and returning the cached results when the same inputs occur again.”</blockquote><p>Before we start with this tutorial — memoization is another technique for performance optimization. These sorts of optimization do take time to design and implement so, make sure you and your team reuse high-quality components by publishing them to component hubs like <a href="https://bit.dev/"><strong>Bit.dev</strong></a>.</p><figure><a href="https://bit.dev/"><img alt="" src="https://cdn-images-1.medium.com/max/800/1*T6i0a9d9RykUYZXNh2N-DQ.gif" /></a><figcaption>Example: exploring React component published on <a href="https://bit.dev/">Bit.dev</a></figcaption></figure><p><strong>All examples displayed in this blog post will be available here:</strong></p><p><a href="https://github.com/itaditya/demo-filtered-list/pull/2">add memo and useMemo by itaditya · Pull Request #2 · itaditya/demo-filtered-list</a></p><p><strong>Let’s check out our app —</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*9p7cuX_NTAFLgjnbkXewvQ.gif" /><figcaption>Demo of the app to be optimized</figcaption></figure><ul><li>Our app shows details of characters in a table.</li><li>We can filter characters by their house.</li><li>We can switch the theme of the app from dark to light and vice-versa.</li><li>We have two states in the app — one for tracking the active house’s id and another for the active theme.</li><li>At any state change, the entire app re-renders.</li></ul><p>You can try the app in this CodeSandbox. Choose a house or switch the theme and you’ll notice that in the Console there’s a log for each component when that component re-renders. If you don’t know what render in React means don’t worry we’ll go over it in this post.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fbtqyn&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fbtqyn&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fbtqyn%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c0b34aa7110086006dfa81932d515d0/href">https://medium.com/media/6c0b34aa7110086006dfa81932d515d0/href</a></iframe><h3>Problems with the App</h3><p>You would have noticed that Table component gets re-rendered anytime a state update happens in App component. It makes sense for Table component to re-render when the <strong>houseId state</strong> changes but it also re-renders when the <strong>theme state</strong> changes. We can optimize the Table component by re-rendering it only when houseId state changes.</p><p><strong>Note —</strong> If the app grew larger and the Table component started rendering lots of components only then optimizing it will be useful. This example is intentionally kept simple so you can easily grasp the main concepts.</p><h3>Understanding the code</h3><p>Our app structure looks like this —</p><pre>App<br> Header<br> Picker<br> Table</pre><p>The App component renders the above three components. From the names you must have guessed Header component renders the title of the app, Picker component renders the list of houses from which you can choose a house and the Table component renders the details of characters based on the chosen house in a table.</p><h4>Peek into the app code</h4><p>Let’s look at the App.js file which contains the main logic including all the components.</p><p><strong>Note — </strong>The mountain of code might look overwhelming and that’s ok. We’ll focus on App.js and then breakdown the other important stuff one by one. Everything in the App.js file will be explained (except styling).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6fbba13591c8af9f3f5226b1ac896abe/href">https://medium.com/media/6fbba13591c8af9f3f5226b1ac896abe/href</a></iframe><p>The <strong>App component</strong> is responsible for these things —</p><ul><li>Render components like Header, Picker &amp; Table and some other JSX.</li><li>Manage state for houseId and theme.</li><li>Use the state and other logic to pass the right props to various components.</li></ul><p>The <strong>Header component</strong> renders the title of the app. Header also renders the button JSX which App component passed to it via children prop.</p><p>The <strong>Picker component</strong> renders the list of Hogwart’s houses. When user clicks on a house, Picker tells the App component which house is selected using the onChange prop. The App component then updates the <strong>houseId state</strong>. Then the Picker component’s <strong>activeHouseId</strong> prop changes and based on the prop an ‘active’ class gets added to the house which is currently selected.</p><p>Then we have the <strong>Table component</strong>. Suppose user selects the house Ravenclaw. So Picker tells App about it and then App component updates the <strong>houseId state </strong>which now becomes the string ‘ravenclaw’. We’ll learn in the next section what exactly state update means. But in short when a state of App component updates, the App component function gets called again.</p><p><strong>Here’s what happens next —</strong></p><ul><li>The stateActiveHouseId variable now has the value ‘ravenclaw’.</li><li>The filterByHouse function gets called again and it returns a new array with only Ravenclaw house characters. This filtered array is stored in filteredCharacters variable.</li><li>App renders the name of first character from the filteredCharacters array in a paragraph.</li><li>The filteredCharacters array is passed to the Table component via charactersList prop.</li><li>Table component loops through the charactersList prop and render each character’s details in a row.</li></ul><p>If you’re wondering why all the state is kept in the App component that’s because —</p><ul><li>The theme state is needed by App component directly as it needs to apply the relevant classname at the top most ‘div’.</li><li>The active houseId state is needed by both Picker and Table component so we need to keep that state in App component.</li></ul><p>Ideally the state should be kept in the deepest component possible. In our case that’s the App component and because of that all child component re-renders when App’s state changes.</p><p>Hope it’s clear to you what the code in App.js file is doing. Now let’s look at React’s update flow in more detail.</p><h3>How React updates the App</h3><p>Before we go on optimizing our component we should have a basic understanding of how React handle updates. When we trigger a state change in App this how React re-renders.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AWGsUg6AAS5XmBHi-XH3qg.png" /><figcaption>How React updates on state change</figcaption></figure><p><strong>Key Takeaways-</strong></p><ol><li>The component whose state has changed will re-render. Then all components inside it will re-render i.e the child function components will get called again. So if the top-most component i.e. App re-renders then all child components will re-render.</li><li>We can also say that a child component will get called again if any of it’s parent’s state changes as only state updates can tell React to re-render. Even child components whose props haven’t changed will get called because React doesn’t compare props by default.</li><li>In function components React only performs two optimizations by default. First, it avoid the re-render process if by <strong>shallow comparison</strong> the new state is equal to the old state. Second, it only updates the DOM nodes which have changed and not the whole DOM as updating DOM is costly.</li></ol><p>I mentioned shallow comparison above. It’s an important concept in React and I’ll be explaining it in detail later in this post.</p><h3>Optimizing Table component</h3><p>Our objective is to make Table re-render only when necessary. So it should <strong>re-render</strong> when <strong>houseId</strong> state changes but should <strong>not re-render</strong> if the <strong>theme state</strong> (or any other state for that matter) changes. This can be done in two steps. In the first step we’ll make Table component re-render only when it’s props changes and in the second step we’ll make sure that props of Table component changes only when houseId state changes.</p><h3>Step 1- Wrap Table with React.memo</h3><p>If some component is doing a lot of heavy lifting then React provides utilities which can help prevent wasteful re-renders of that component. One of those is React.memo.</p><p>React.memo is an <a href="https://devadi.netlify.app/blog/react-renderprops-hoc#higher-order-components-hoc">HOC</a> which takes a component and returns an enhanced component. When React re-renders this enhanced component it will <strong>shallow compare</strong> the new props object passed to this component with the old one. If shallow compare says that props are same as last time then React skips re-rendering the enhanced component (and therefore all other component it re-renders).</p><p>You might be wondering why React doesn’t shallow compare props by default. That’s because there’s a high chance the comparison will be false and in that case we’ll pay both the comparison cost and the re-render cost.</p><p>Let’s apply React.memo on the Table component and you’ll see what I mean.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/76b32dfc5572dd6735a732f1021d7b49/href">https://medium.com/media/76b32dfc5572dd6735a732f1021d7b49/href</a></iframe><p>Take a look at the CodeSandbox below. Surprisingly everything behaves exactly like it did before. The reason there is no noticeable change is that we pass an <strong>array </strong>in the props. But why 🤔 ? Let’s take a closer look.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fjx4y8&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fjx4y8&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fjx4y8%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd4bd6c3ccf46877a22221e05984e1b2/href">https://medium.com/media/fd4bd6c3ccf46877a22221e05984e1b2/href</a></iframe><h4>Shallow Comparison</h4><p>Two objects are equal by shallow comparison if —</p><ol><li>Both objects have the same keys.</li><li>The values for each key in both objects are <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Identity"><strong>strictly equal</strong></a>.</li></ol><p>So if we have three objects like</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f88bd26fbdfc8a7474bd5977452e86c/href">https://medium.com/media/8f88bd26fbdfc8a7474bd5977452e86c/href</a></iframe><p>Then shallow comparing car1 with car2 will happen like this —</p><ol><li>Both car1 &amp; car2 have the same keys (color and model)?<br>Yes ✅</li><li>The values for color key ( car1.color === car2.color) are <strong>strictly equal</strong>? <br>Yes ✅</li><li>The values for model key (car1.model === car2.model) are <strong>strictly equal</strong>? No ❌</li></ol><p>For that reason shallow comparing car1 with car2 will give us false. But when we <strong>shallow compare car1 with car3 it will give us true</strong>.</p><p>This still doesn’t answer why passing an array in the props made the React.memo useless. For that we also need to understand strict equality.</p><h4>Strict Equality</h4><p>Let’s see the result of strict equality (===) on some items.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b553bf9597ec512f89584505caedd33/href">https://medium.com/media/5b553bf9597ec512f89584505caedd33/href</a></iframe><p>You might be surprised by the behavior of strict equality with arrays (same with objects and functions too). If that’s the case definitely read the below article by Dmitri. It explains these things in more detail.</p><p><a href="https://dmitripavlutin.com/how-to-compare-objects-in-javascript/">How to Compare Objects in JavaScript</a></p><p>In a nutshell strictly comparing two arrays means checking if they have the same memory location or reference. Try this challenge on <a href="https://gist.github.com/itaditya/6dfce9abecc8cbf54a763de3521e3559"><strong>strict equality</strong></a><strong> </strong>if you wanna be sure that you got everything. Let me know in comments how you perform.</p><p>I promise the time we have spent on <strong>shallow comparison </strong>will definitely come in handy to you as its used a lot in React. State updates, useEffect, useMemo, useCallback and React.memo all depend on it.</p><h4>Shallow Comparison of Table props</h4><p>We can now understand the behavior of React.memo when we passed an array as a prop.</p><p>When App re-renders, the <strong>filterByHouse</strong> function gets called which generates a <strong>new array</strong> of characters. This array is passed as<strong> charactersList</strong> prop. That means React will perform a shallow comparison like</p><pre>shallowCompare(oldProps, newProps)</pre><p>Because of this each item in the props objects will be checked for strict equality. We only have charactersList array so this will happen —</p><pre>oldProps.charactersList === newProps.charactersList // false</pre><p>As the filterByHouse function returns a new array the reference of the two charactersList arrays being compared are different. Because of that shallow comparing old props with new props will give us false and so React will conclude that props have changed and the Table component needs to re-render.</p><p>Let’s look at the effect of passing different values in props on a component wrapped with React.memo.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fzgku3&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fzgku3&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c127a188a64d0ab880ff8dda0fd02f4/href">https://medium.com/media/7c127a188a64d0ab880ff8dda0fd02f4/href</a></iframe><p>So we need a way to ensure that comparing the new props with the old one gives us <strong>true. </strong>That brings us to the last step.</p><h3>Step 2- Babysitting React.memo</h3><p>We saw that just wrapping Table with React.memo doesn’t solve our problem and that’s because React.memo does shallow comparison by default. Now there are two ways to solve it.</p><ul><li><strong>Deep comparison — </strong>React.memo can take a comparison function as the second argument. This function can be used for deep comparing the old props with the new one. It’s done like React.memo(MyComp, myCompareFunc)<br>But as the comparison is deep, it has to go through all the nested properties of both objects. The higher the nesting the slower it will be. Instead of deep comparing 100 items just rendering them might be faster.</li><li><strong>Preserving reference — </strong>The problem we faced with shallow compare was that reference to charactersList array was different on every render. But what if we cache the filtered array such that it only generates a new array when the houseId state changes? That way if the houseId is same as the last time it returns the same old array and so Table component won’t re-render. Let’s see how to do it in React.</li></ul><h4>Preserving reference with useMemo hook.</h4><p>The main idea of useMemo is to utilize the same last result when certain conditions are met. Let’s look at how it is used.</p><ol><li>We pass two arguments to useMemo. First is a function which performs some calculations and return the result. Second argument is an array called the dependency array.</li><li>On the first render the result of calling the function (first argument) is stored and useMemo returns that result.</li><li>On every subsequent render, the dependency array is shallow compared with it’s previous value. If shallow comparison gives false the function gets called again.</li><li>The new result returned by the function is then stored by useMemo and useMemo then returns this result.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9acd221ee156671bba85ff9b6894061/href">https://medium.com/media/e9acd221ee156671bba85ff9b6894061/href</a></iframe><p>Let’s look at how useMemo is working in our app —</p><ol><li>On first render, <strong>filterByHouse </strong>function is called and it returns an array including all characters. useMemo store this array and then returns it so Table can then render it on screen.</li><li>User selects a house so the <strong>houseId state changes</strong>, because it’s listed in the dependency array, useMemo calls filterByHouse again, a new array is generated and so Table component re-renders.</li><li>User changes the theme so <strong>theme state</strong> changes. Since the items in dependency array is same as last time, useMemo just returns the same old filteredCharacters array (same reference) without calling filterByHouse function.</li><li>Since the Table component (wrapped with React.memo) now gets the charactersList array with same reference as last time it doesn’t re-render.</li></ol><p>This becomes apparent in this recording</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*1GanmqYc3ueYFu6sJ-GWkw.gif" /><figcaption>Table component re-renders only when houseId state changes</figcaption></figure><p>Here’s the <a href="https://github.com/itaditya/demo-filtered-list/blob/optimized/src/App.js">full App.js file</a> with both React.memo and useMemo added.</p><p><strong>Note — </strong>useMemo only stores the last value and not all the previous values. So if you change from Ravenclaw to Slytherin and back to Ravenclaw then <strong>filterByHouse</strong> will get called 3 times. If <strong>filterByHouse </strong>is going to be an expensive operation then it’s better to memoize it outside of React using lodash’s memoize or your own custom implementation.</p><p>You can see all the changes we did in this <a href="https://github.com/itaditya/demo-filtered-list/pull/2">GitHub PR</a> —</p><p><a href="https://github.com/itaditya/demo-filtered-list/pull/2">add memo and useMemo by itaditya · Pull Request #2 · itaditya/demo-filtered-list</a></p><p>and you can see the optimized app in this CodeSandbox —</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2F1eszv&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2F1eszv&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F1eszv%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6dc766b7ea35e195977a00dc3232d9b/href">https://medium.com/media/d6dc766b7ea35e195977a00dc3232d9b/href</a></iframe><p><strong>Negative Optimizations</strong></p><p>You must have realized now that optimizing the app is not like flipping a switch. You have to actually check how the changes affect the app. Here’s another case where React.memo by itself will just harm the performance.</p><p>Let’s say you’re passing JSX as children prop to a component wrapped with React.memo. Now these things will happen.</p><ul><li>JSX passed to children prop gets transformed into React.createElement() i.e. a function call.</li><li>React.createElement() returns an object representation of children JSX.</li><li>Since the function returns an object, shallow compare between previous children prop and new children prop will always be <strong>false </strong>even if the children JSX looks same as before.</li></ul><p>You can try this on Header component as it accepts a children prop to render the theme switching button. Actually, that’s the only reason I included it in the app.</p><p>Also I didn’t optimize the Picker component. It re-renders on theme state change too but as it’s a tiny component it’s re-render won’t cause any performance issues. For learning purposes you can try optimizing Picker component. It will also need something more then React.memo because we are passing a function as prop to it. Read about useCallback if you’re interested.</p><p><strong>TL;DR —</strong> don’t start wrapping all components with React.memo blindly. It can lead to negative optimizations as well as premature optimizations which are not good for maintainability.</p><p>If you like this article smash the clap button and share it with your friends. You can read more <a href="https://devadi.netlify.app/blog/async-await-hell">articles on my blog</a>.</p><p><a href="https://devadi.netlify.app/blog/async-await-hell">How to escape from the async/await hell</a></p><p>Follow me on <a href="https://twitter.com/dev__adi">Twitter (https://twitter.com/dev__adi)</a> if you have questions or if you want to stay up-to-date with cool developer tips and interesting technologies.</p><h3></h3><p></p><h3>Learn More</h3><ul><li><a href="https://blog.bitsrc.io/5-recommended-tools-for-optimizing-performance-in-reactjs-29eb2a3ec46d">5 Recommended Tools for Optimizing Performance in ReactJS</a></li><li><a href="https://blog.bitsrc.io/code-principles-every-programmer-should-follow-e01bfe976daf">Code Principles Every Programmer Should Follow</a></li><li><a href="https://blog.bitsrc.io/building-with-react-for-all-platforms-5-top-frameworks-and-tools-affd5baf3de3">Building with React for All Platforms: Top Frameworks and Tools</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec52447b09ba" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bitsrc/optimize-your-react-app-with-react-memo-ec52447b09ba">Optimize Your React App with React.memo</a> was originally published in <a href="https://medium.com/bitsrc">Bits and Pieces</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Better Components with TailwindCSS]]></title>
            <link>https://medium.com/@adityaa803/better-components-with-tailwindcss-2544b1774d4?source=rss-9c555799c00e------2</link>
            <guid isPermaLink="false">https://medium.com/p/2544b1774d4</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[tailwind-css]]></category>
            <category><![CDATA[vuejs]]></category>
            <dc:creator><![CDATA[Aditya Agarwal]]></dc:creator>
            <pubDate>Sun, 12 Jan 2020 07:06:31 GMT</pubDate>
            <atom:updated>2020-01-13T11:20:51.853Z</atom:updated>
            <content:encoded><![CDATA[<p>TailwindCSS is great for building reusable components of your design system. The component itself can be written in ReactJs or VueJs and we’ll get the same benefit.</p><h3>But How?</h3><p>Today, I’ll just talk about one reason and that is <strong>Encapsulation</strong>. When we write a component we want to allow some customizations but on the other hand, we also want to prevent full access to the internals of a component. That is to say we want to expose a public API and only allow customisation from that public API.</p><p>First I’ll shed some light on why traditional styling doesn’t provide Encapsulation.</p><h3>ClassNames is a public API.</h3><p>In React, a components public API is made with props and in Vue we have props + slots. But we are forgetting one thing. If a component uses CSS classes for styling then we are unknowingly providing another public API. Because all CSS classes are global, any consumer of the component can override the internal styles of a component.</p><p>Take a look at this example</p><pre>function Button({ icon, size=&#39;normal&#39;, children, ...props }) {<br>  return (<br>    &lt;button {...props} className={`btn btn-${size}`}&gt;<br>      &lt;span className=&quot;btn-icon&quot;&gt;<br>        &lt;Icon icon={icon} /&gt;<br>      &lt;/span&gt;<br>      {children}<br>    &lt;/button&gt;<br>  );<br>}</pre><p>It’s a simple Button component which can render text and an icon. There is a size prop as well with which user can render a normal button or a large buttton. It makes sense because we don&#39;t want user to render a button of any size. We want the size to be constrained. Also this way we can scale the icon according to size of button. If we give user the full control then they might forget increasing the size of icon while making a large button.</p><p>So we have two requirements-</p><ol><li>User should only render a normal or large size button.</li><li>Everything inside button like font and icon should scale along with button size.</li></ol><p>But is the current implementation really following the two requirements?<br> The answer is <strong>No</strong>.</p><p>Because user knows about the two classNames btn &amp; btn-icon they can customise both the elements in any way they want. Assume user writes this CSS-</p><pre>.btn {<br>  font-size: 100px;<br>  padding: 10px;<br>}<br><br>.btn-icon {<br>  font-size: 20px;<br>}</pre><p>All of the hard work you did to keep the scale of icon and button in sync is now wasted. User has unregulated control, it’s chaos.</p><p>To put it in short there are two problems with using classNames like this for components of a design system-</p><ol><li>User has full control of the styling and you can’t add constraints.</li><li>If you change the internal structure, user’s applications can break.</li></ol><p>I’m a lot more scared about the second problem. Because now the user relies on the internal structure of the component you can’t modify the internals carefree. You cannot change the btn-icon class to something else. And that&#39;s just one thing. Imagine all the classes a component is made of. Once you publish the component you have tied yourself in a corner, you cannot modify anything you can just add new things. And when you just add new things your API surface becomes larger and more complex.</p><p>This xkcd comic is exactly what I’m talking about</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/278/0*tqBH7KhjGmh0muZ6.png" /></figure><h3>Tailwind to the rescue</h3><p>TailwindCSS provides a simple solution for this. Just don’t use classes this way. If you don’t have a catch-all btn class then users won&#39;t be able to override it.</p><p>A Button styled with TailwindCSS would look like this-</p><pre>function Button({ icon, size=&#39;normal&#39;, children, ...props }) {<br>  return (<br>    &lt;button {...props} className={`bg-green text-${size}`}&gt;<br>      &lt;span className={`bg-gray-600 text-${size}`}&gt;<br>        &lt;Icon icon={icon} /&gt;<br>      &lt;/span&gt;<br>      {children}<br>    &lt;/button&gt;<br>  );<br>}</pre><p>What is important to notice is that the entire component is made of utility classes. These classes just do one small thing and each class might appear in multiple components. A user would not override bg-gray-600 because that would break all those components which use bg-gray-600 class. Earlier the user knew that btn-icon would just affect the icon inside Button component so they modified it carefree but now they can&#39;t.</p><p>Now you have the control on what things you want the user to give control of. User can’t even change the color of button if you don’t provide a prop for it.</p><p>Hope this article helped you understand one benefit of TailwindCSS. I’d be writing more about Tailwind and design systems in general so if you’re interested in that give me a follow here or on <a href="https://twitter.com/dev__adi">Twitter</a>.</p><p><em>Originally published at </em><a href="https://dev.to/itaditya/better-components-with-tailwindcss-4b0h"><em>https://dev.to</em></a><em> on January 12, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2544b1774d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Highly Customizable Tab Component with Vue.js Slots]]></title>
            <link>https://medium.com/bitsrc/highly-customizable-tab-component-with-vue-js-slots-7e1cee400a7c?source=rss-9c555799c00e------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e1cee400a7c</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Aditya Agarwal]]></dc:creator>
            <pubDate>Wed, 06 Feb 2019 15:40:25 GMT</pubDate>
            <atom:updated>2019-03-26T14:36:32.182Z</atom:updated>
            <content:encoded><![CDATA[<h4>Build a highly reusable and customizable Tab component</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*w_t-cwnaCB0RNVdp.jpg" /></figure><p>Vue.js has an amazing feature called <strong>Slots</strong> that’s modeled after the current <a href="https://github.com/w3c/webcomponents/blob/gh-pages/proposals/Slots-Proposal.md">Web Components spec draft</a>. If a component is using slots then we can fill whatever content we want in those slots. This way the component can deal with all the logic and let the component’s user provide the view part of it.</p><p>For example, suppose you are building a library for developers to easily integrate payment gateway in their application. Now instead of providing a generic button to start the payment, you can keep a slot in the component in which a developer can insert their themed button.</p><p>Sounds cool? Great, read on to learn how we can use Slots to make highly customizable components.</p><p><strong>Tip</strong>: Share reusable components <a href="https://bit.dev/">with <strong>Bit</strong></a>. Then you can easily find and use them in every app you’re building, and share with your team. Try it.</p><figure><a href="https://bit.dev/"><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Yhkh7jbS5Mx9uP96Y88pZg.gif" /></a></figure><h3>What we’ll be building?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*XP5uV1uRIGd55ny-uQf38A.gif" /><figcaption>The</figcaption></figure><p>We have a window with three tabs showing names of Harry Potter characters. Clicking on the name of character shows more information about that character.</p><h3>How can slots help here?</h3><p>I have seen many Tab implementations so far and what most of them lack is customisability. An implementation might take a list of tab content like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hoNbz0OE-Q_URIo1Twl1Ww.png" /></figure><p>Here we can only pass strings for each tab. What if we want to add videos in the Tab’s panel? What if we decide we want a badge of each character’s house right next to their name in the top bar tab list? Also, there is no way to attach styles to the individual parts of the Tab component.</p><p>How about we allow the user of this component to pass a Vue component instead of a string? Now that component can have anything we want and the Tab component will render it. That’s actually not that bad but who wants to make a new component for each tab just so we have can add a class or insert an image.</p><p>Another downside is that in the component where the Tab component is used, we are <strong>moving the markup away from the template section</strong> to the script section. That is completely opposite of what should actually be done. What we want is that the content should remain in the template section and the script section should only contain the logic.</p><p>This is where Vue.js slots step in. A Vue.js component can have a number of named slots and when we use that component we can tell what markup should go in each slot. A slot can contain strings, HTML tags or other Vue.js components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y2iai-RuLypQOMSEDkyHKw.png" /><figcaption>App component uses slots of MyComponent</figcaption></figure><h3>Implement Tab Component with slots</h3><p>So far we have seen how Vue.js slots let us customize the markup input we send to a component. But how do we actually use it for making Tabs?</p><p>First, let’s look at how our new implementation of Tab Component will be used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PtP5pN4vBzoTsg_uQ4lKZQ.png" /><figcaption>TabCard Component usage in App Component</figcaption></figure><p>Lots of thing going on here. Let’s understand each of them piece by piece.</p><h4>TabCard Props</h4><p>We are passing two props to TabCard component, <strong>initialTab</strong> string and <strong>tabs</strong> array.</p><p>The <strong>tabs prop </strong>contains a list of unique names for each tab. Each tab (including the tab’s detail panel) will be identified with its corresponding unique name. So for James Potter, the unique name is ‘james’.</p><p>The<strong> initialTab prop</strong> is used to inform TabCard which tab should be active at first. If we want that by default Lily Potter’s details are shown, i.e. ‘lily’ tab is active we will have to pass ‘lily’ as the value to initialTab prop.</p><h4>TabCard Slots</h4><p>For each tab, we need two slots one to show in the tab’s head and one for its panel which contains all the information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7hdOFINmeo2n90z0Rh66bA.png" /><figcaption>Illustration to show different slots</figcaption></figure><p>For Severus Snape, the slots are <strong>tab-head-snape</strong> and <strong>tab-panel-snape</strong>.</p><p>In the slots we are free to put anything. If we want to have the Gryffindor house symbol next to the word James in the tab head, we can just insert the image in the <strong>tab-head-james</strong> slot. If we want to insert something in the description, we will have to use the <strong>tab-panel-*</strong> slots.</p><p>Now that we have a clear idea of how we intend on using the TabCard component let’s see how it is actually implemented.</p><p>Note- There are some markup and class names solely for designing purposes. I am not including the corresponding styles so that we can focus on the logic part.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_JB_6oRY0jYD0PHz9SaMpA.png" /><figcaption>TabCard component template section</figcaption></figure><p>There are some important things happening here.</p><ol><li>We use <strong>v-for</strong> directive to loop over the <strong>tab</strong> list provided as a prop to TabCard.</li><li>We bind the ‘<strong>tab-head — active</strong>’ class if the <strong>activeTab</strong> data property matches the tab name.</li><li>We attach a click handler which when called passes it’s tab name as argument.</li></ol><p>Apart from all that, there are two major things happening here which looks pretty unusual and, spoiler, both of them have to do with slots.</p><p>The thing is, till now I have kept a secret from you all. The name property of a slot doesn’t have to be a static string. It can be binded to a computed property or to a value returned by a component’s method.</p><p>In the tab’s head slot we are calling <strong>tabHeadSlotName </strong>method of TabCard component and passing it the tab name as argument. This method (which we’ll see in some time) will use the tab name and will be binded to the slot name.</p><p>In the tab’ panel slot, we only want to render the active tab’s markup so we use the <strong>tabPanelSlotName </strong>computed property. The <strong>tabPanelSlotName</strong> computed property uses <strong>activeTab</strong> data property to compute the name for the slot panel.</p><p>Let’s look at the script section of the TabCard component to get a full picture of the implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WC5pQYsRTPEodrnzKexEfA.png" /><figcaption>TabCard component script section</figcaption></figure><p>We have a data property called <strong>activeTab </strong>which will be used to control which tab is currently active. It is assigned the value of initialTab prop. This way the default active tab can be given as a prop.</p><p>Next, we have a computed property <strong>tabPanelSlotName </strong>which returns a slot name for tab panel based on the activeTab data property. So if the ‘james’ tab is active, the value of tabPanelSlotName will be ‘tab-panel-james’.</p><p>Many of you will be thinking, with all the dynamic slot name shenanigans what do we actually achieve? Well… let me enlighten you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/0*dUGg_URcZSh1z8Mb.png" /></figure><p>Vue will only render the slots which it finds inside the TabCard component’s template. So when the <strong>tabPanelSlotName </strong>is ‘tab-panel-lily’ Vue will only render Lily’s panel. When the <strong>tabPanelSlotName </strong>is ‘tab-panel-snape’, Vue will only render Snape’s panel.</p><p>At last we have two methods, tabHeadSlotName and switchTab.</p><p><strong>tabHeadSlotName </strong>method uses it’s argument tabName to generate the tab head slot name. This method will be called for each tab. When it receives ‘james’ as argument it returns ‘tab-head-james’. When it receives ‘lily’ it returns ‘tab-head-lily’.</p><p><strong>switchTab </strong>method uses it’s argument tabName to change the activeTab data property.</p><p>And this is all we need for making our highly customizable Tab components.</p><h3>Conclusion</h3><p>In this article, my main motive was to teach you some advanced usage of Vue slots. I hope the concrete examples were more helpful than just a basic usage tutorial. I encourage you to experiment with the above examples using this <a href="https://codesandbox.io/s/3r01nk5q41">codesandbox</a>.</p><p>If you want to read more of such insightful posts, follow me on <a href="https://twitter.com/dev__adi">Twitter</a> or subscribe to <a href="https://buttondown.email/itaditya">my newsletter</a>. Thanks for reading 🙏 . Please feel free to comment and ask anything…</p><h3>Learn more</h3><ul><li><a href="https://blog.bitsrc.io/11-vue-js-component-libraries-you-should-know-in-2018-3d35ad0ae37f">11 Vue UI Component Libraries You Should Know In 2019</a></li><li><a href="https://blog.bitsrc.io/5-tools-for-faster-development-in-react-676f134050f2">5 Tools for Faster Development in React</a></li><li><a href="https://blog.bitsrc.io/how-to-easily-share-react-components-between-projects-3dd42149c09">How to Share React UI Components between Projects and Apps</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e1cee400a7c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bitsrc/highly-customizable-tab-component-with-vue-js-slots-7e1cee400a7c">Highly Customizable Tab Component with Vue.js Slots</a> was originally published in <a href="https://medium.com/bitsrc">Bits and Pieces</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Interactive Text Animation with React Hooks]]></title>
            <link>https://medium.com/bitsrc/interactive-text-animation-with-react-hooks-f89820af8301?source=rss-9c555799c00e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f89820af8301</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Aditya Agarwal]]></dc:creator>
            <pubDate>Wed, 16 Jan 2019 15:36:27 GMT</pubDate>
            <atom:updated>2019-04-01T09:44:49.939Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to animate headings that respond to mouse movements using React Hooks, CSS Modules, CSS variables and clip-path.</h4><p>I was intrigued after watching Peter Tichy’s <a href="https://www.youtube.com/watch?v=dE-B0j_gt_Y">video tutorial</a> in which he recreates the interactive animation of <a href="http://fleurmoreau.fr/">this</a> website.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FdE-B0j_gt_Y%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DdE-B0j_gt_Y&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FdE-B0j_gt_Y%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/aa3d0b2866a06efce6a10a67c7d5d9ae/href">https://medium.com/media/aa3d0b2866a06efce6a10a67c7d5d9ae/href</a></iframe><p>I decided to build the same but with the hot new tech like React Hooks, CSS custom properties, clip-path and CSS Modules. Building these small but complete UI pieces really helps in getting a good grasp of the tools without worrying about completing and maintaining large side-projects that will never see the light of the day.</p><p><em>Use Create React App v2.0 and React v16.8.0 or above for this tutorial.</em></p><h3>What we’ll be building</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*5a0yzOuotYnMJpG1d7MLXw.gif" /><figcaption>I love Messi</figcaption></figure><p>When mouse is hovered over Lionel Messi, some part of the text shines with yellow color.</p><p>Although not used here, it’s recommended to manage your React components with <a href="https://github.com/teambit/bit">Bit</a>, to make them organized and reusable for you and your team. It will save a lot of time and work in your next app. Give it a try.</p><p><a href="https://bit.dev/">Bit. Composable software.</a></p><h3>Let’s start hacking</h3><p>Our React application will have a src/ directory where we will make all the code changes. The file structure will look like this.</p><pre>$ tree src/</pre><pre>|__ index.js<br>|<br>|__ styles.css<br>|<br>|__ AnimatedText.js<br>|<br>|__ AnimatedText.module.css</pre><p>The index.js file is the entry point to our application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t82K4zBcq-tVc96a4n1vyA.png" /><figcaption>index.js</figcaption></figure><p>We have imported styles.css file and AnimatedText component. The styles.css file only contains a handful of style declarations mainly to reset the browser styles and center align everything on the page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o5c6xxkVBamVXhRJJyY-NA.png" /><figcaption>styles.css</figcaption></figure><p>The AnimatedText component uses three main props — textColor, overlayColor and children.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GxUwt6NWX_ybgja-j9BwBQ.png" /><figcaption>AnimatedText.js</figcaption></figure><p>We import AnimatedText.module.css CSS Module and assign the corresponding classes to the elements. There are two headings, the second one will be styled to overlap the first one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3N8M3EocLlxx-GuPFSG7JQ.png" /><figcaption>AnimatedText.module.css</figcaption></figure><p>With CSS Modules we can reuse all the declarations of one class in another with the help of composes keyword. That way we can ensure that both the headings have the same base styling. Then we add some more declarations in the second heading to make it an overlay.</p><p>We can see that the first heading (red colored) is entirely hidden because the second heading (golden colored) completely overlaps it. Now, we’ll use clip-path to clip the second heading along a certain shape.</p><h4>Clipping the overlay heading</h4><p>The clip-path property is used to clip text to a specific shape.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rdTwgcGiL0mnNvBgFqYD7w.png" /><figcaption>AnimatedText.module.css (updated)</figcaption></figure><p>The value of clip-path property is copied from the website linked in the beginning. What it does is difficult to understand by just looking at code. So let’s check the result for certain values of maskX and maskY.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9mLfcSClarxm-xVcxAs9-A.png" /><figcaption>maskX = 50, maskY = 0</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vaL7fanHZ6lmRbMICWvpEg.png" /><figcaption>maskX = 50, maskY = 50</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vUpndJ2yzU3ro4I_QWIjoA.png" /><figcaption>maskX = 80, maskY = 0</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HMzxOSsj0AoK6BP-F6EI9A.png" /><figcaption>maskX = 80, maskY = -100</figcaption></figure><h4>Listening to Mouse movements</h4><p>We add onMouseMove and onMouseOut props to the the animated text container. The mouse move handler uses the state setter provided by the useState React Hook to set the mousePos to the new mouse position. React then assigns the mousePos state to the maskX and maskY CSS variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-V2Z6EHv57zkHSTwL6L9sg.png" /></figure><p>When the mouse leaves the container, handleMouseOut function resets the state to initialMousePos.</p><p>The only thing left is to calculate the value of newX and newY. For that we will find the width of the animated text container and use it to find a percentage for newX and newY. The complete implementation of AnimatedText component will look like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1cefde98abd97b2c8f5c94d811653b81/href">https://medium.com/media/1cefde98abd97b2c8f5c94d811653b81/href</a></iframe><h3>Conclusion</h3><p>With that, we are done with the implementation of the Interactive Text Animation. The code is available in this <a href="https://codesandbox.io/s/z6047rj9vx">codesandbox</a>. Here are some <a href="https://bit.dev/giladshoham/react-hooks">useful hooks with</a> Bit.</p><p>If you like my work, don’t be shy about clapping. Follow me on <a href="https://twitter.com/dev__adi">Twitter</a> and <a href="https://medium.com/@adityaa803">Medium</a> or subscribe to <a href="https://buttondown.email/itaditya">my newsletter</a> to get updates on my latest content. Thanks for reading 🙏 Please feel free to comment and ask anything…</p><h3>Learn more</h3><ul><li><a href="https://blog.bitsrc.io/5-tools-for-faster-development-in-react-676f134050f2">5 Tools for Faster Development in React</a></li><li><a href="https://blog.bitsrc.io/11-react-component-libraries-you-should-know-178eb1dd6aa4">11 React UI Component Libraries you Should Know in 2019</a></li><li><a href="https://blog.bitsrc.io/how-to-easily-share-react-components-between-projects-3dd42149c09">How to Share React UI Components between Projects and Apps</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f89820af8301" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bitsrc/interactive-text-animation-with-react-hooks-f89820af8301">Interactive Text Animation with React Hooks</a> was originally published in <a href="https://medium.com/bitsrc">Bits and Pieces</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ideal boilerplate for reusable React components]]></title>
            <link>https://medium.com/@adityaa803/ideal-boilerplate-for-reusable-react-components-35b72c0d1b11?source=rss-9c555799c00e------2</link>
            <guid isPermaLink="false">https://medium.com/p/35b72c0d1b11</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[components]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Aditya Agarwal]]></dc:creator>
            <pubDate>Fri, 11 Jan 2019 09:00:02 GMT</pubDate>
            <atom:updated>2019-01-11T09:00:02.422Z</atom:updated>
            <content:encoded><![CDATA[<p>Getting started with a functional React component is easy but when we are building reusable components we should keep somethings in mind.</p><ol><li>We can render custom markup inside the component to make it more flexible.</li><li>We can add classes to the component for modifying the styling of the component.</li><li>We can set attributes of the element the container is wrapping. (e.g. aria attributes, data attributes);</li></ol><p>To ensure that our React component can support all of them we should use the following code as boilerplate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zZPWPK3XYNWzw3Su.png" /></figure><p>First we destructure all the props we need in our component and then collect all the remaining props in props variable.</p><p>Then we merge the className prop with our own component’s classes.</p><p>At last, we assign the className and spread the other props and render children inside the div.</p><p>We can then use it like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9S61gZ9io-nhfhF2" /></figure><p><strong>PRO TIP</strong>: in our component to avoid hard-coding the div element, we can implement as prop in the component like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7h1kSueFUsHuF_lN.png" /></figure><p>then it will be used like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8HhNBRwQtrv_WU9c.png" /></figure><p>This is a cross-post from my <a href="https://buttondown.email/itaditya/">newsletter</a>. Subscribe to directly get informational content right in your inbox.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fbuttondown.email%2Fitaditya%3Fas_embed%3Dtrue&amp;url=https%3A%2F%2Fbuttondown.email%2Fitaditya&amp;image=https%3A%2F%2Fbuttondown.s3.amazonaws.com%2Ficons%2Fb3265782-1d32-4262-b647-943b02cca83c.png%3FAWSAccessKeyId%3DAKIAJEXF6S6TCOKT7N3Q%26Signature%3DirOcCCIzDw6j%252Bq35Pt1gG5eZaao%253D%26Expires%3D1547200718&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=buttondown" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3bd33c1078eace77259193ba4ea7d6b4/href">https://medium.com/media/3bd33c1078eace77259193ba4ea7d6b4/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35b72c0d1b11" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>