<?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 Felix Tan on Medium]]></title>
        <description><![CDATA[Stories by Felix Tan on Medium]]></description>
        <link>https://medium.com/@regalius?source=rss-8e427cea571f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ivjbbyohXBdtrJ1TgJhZnw.jpeg</url>
            <title>Stories by Felix Tan on Medium</title>
            <link>https://medium.com/@regalius?source=rss-8e427cea571f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 20:34:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@regalius/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[A Christmas Treats for you!]]></title>
            <link>https://medium.com/tokopedia-engineering/a-christmas-treats-for-you-a13c81f2738b?source=rss-8e427cea571f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a13c81f2738b</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[tokopedia]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Felix Tan]]></dc:creator>
            <pubDate>Tue, 25 Dec 2018 09:47:05 GMT</pubDate>
            <atom:updated>2018-12-25T14:12:39.148Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Christmas Treats for you!</h3><h4>We’re happy to announce that we’re open sourcing <a href="https://tokopedia.github.io/treats">Treats</a>, our internal React framework.</h4><p><em>Co-authored with: </em><a href="https://medium.com/@martinock"><em>Martino CK</em></a><em> , </em><a href="https://medium.com/@alchristleo96"><em>Alchrist L</em></a><em>, </em><a href="https://medium.com/@fadlioctora"><em>Fadli T</em></a><em>, </em><a href="https://medium.com/@williamcandra56"><em>William C</em></a><em>, </em><a href="https://medium.com/@salmanalfariz24"><em>Salman AF</em></a><em> and other Treats core contributor team members.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BiM__u5O1C5Rz0LOcwiDww.jpeg" /><figcaption>Treats — Tokopedia React Development Kits</figcaption></figure><p>Howdy fellow engineers and beloved readers, first of all, we would like to say: Merry Christmas!</p><p>This Christmas feels very special to us because at this special time of the year, we’re able to share and give back to the Open Source community. Tokopedia had always been standing on the shoulder of the giants, we build stuff to solve problems with many open source technologies, so it is only natural for us to give back to the community itself.</p><p>We’re happy to announce that we’re open sourcing <a href="https://tokopedia.github.io/treats">Treats</a>. Treats is a React framework that provides server-side rendering, code-splitting, localization, state-management, etc with zero configuration experience for beginners but easily configurable for power users.</p><h3>But first, let’s start with The Why</h3><p>You might ask, why another React framework? Isn’t there already so many React frameworks out there in the open, why reinventing the wheel? Well, here’s the story behind it all!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*5m25pmrAZzfenMQ97jLZQg.jpeg" /><figcaption>CMS or Custom? (Commit Strip) <a href="http://www.commitstrip.com/en/2015/04/03/cms-or-custom/">http://www.commitstrip.com/en/2015/04/03/cms-or-custom/</a></figcaption></figure><p>Before we adopted React as our <em>de-facto</em> Javascript frontend framework, our web frontend codebase were mainly written in combination of Perl, jQuery and some AngularJS 1.x on a single monolithic repository that is shared with more than 300 other fellow software engineer nakamas. With the monolithic stacks, each team only have two scheduled deployments per-week to avoid conflicts between deployment and any unwanted regression. With project at Tokopedia’s scale and our need for agility to stay ahead of the competition, this technology stack and workflow created some dire problems:</p><ol><li>Scheduled deployment means slower iteration and unnecessary wait before teams can release their feature.</li><li>Doing Test Driven Development (TDD) is hard on our current stack, no unit tests and integration tests led to unwanted regression and many unpredictable bugs.</li><li>Refactoring becomes another unnecessary challenge, because we have to skim and figure out what our spaghetti codes are doing to avoid breaking them.</li><li>Maintaining two separate codebases (Perl and AngularJS) are unavoidable for interactive web application that needs server-side rendering (for SEO purpose, etc).</li><li>Web app performance were bad because let alone thinking about performance, it is already magical for us to ship our hard to test, hard to maintain frontend codes to production.</li></ol><h4>The make it better 1.0</h4><p>Two years ago, when <a href="https://labs.spotify.com/2014/03/27/spotify-engineering-culture-part-1/">Spotify Model</a> and Tribe system were introduced in Tokopedia, things were getting messier. Each tribe had their own ideas about how we should improve our frontend codebase and there were no standards at how we should do it. Some tribes used Go with Go template as their frontend engine, some uses React with modifying different variations of starter kits that we could find on the market, AngularJS and Go template, some even tried to marry VueJS with Go template. Everything were sticked and glued using NGINX proxy, server-side include, and God knows what else.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*bd6HWuODNCEY4OxJJzUygQ.jpeg" /><figcaption>When We Leave Coders to do Their own Thing (Commit Strip) <a href="http://www.commitstrip.com/en/2017/03/16/when-we-leave-coders-to-do-their-own-thing/">http://www.commitstrip.com/en/2017/03/16/when-we-leave-coders-to-do-their-own-thing/</a></figcaption></figure><p>Treats first version were initially one of the variations of React framework that we used back then to migrate our Perl+jQuery+AngularJS codes to React. The difference is, Treats were built from scratch rather than modifying other framework. By building it from scratch, we can modify it as much as we want to cater our needs without any restrictions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*SzkLMwgYDsgbkwHPFYAiWg.gif" /><figcaption>[GIF] Showcase of some pages that’s powered by Treats initial version</figcaption></figure><blockquote>There’s still enough rooms in this world for another React framework, let’s build one! — React hipsters on the team</blockquote><p>After running it well and stable enough on the first iteration of Treats for months, we decided that it would be a great idea to ship our codes as a full-fledged framework so it would be available for everyone who wants to migrate their codebase to React.</p><h4>One framework to serve us all</h4><p>The problem with creating a framework on an already ongoing sporadic improvements is to be able to accommodate as many if not every needs of every person in the room, yet making sure the core of the framework itself isn’t too bloated with so many non-trivial implementations that should be done on the application level rather than on the framework itself. When we’re building a framework that would be used across teams as large and diverse as Tokopedia’s, we also need to make it easy to push updates to each of the application that’s built on top of the framework.</p><p>We could just throw a skeleton starter kit to each team and let them build their app based on that, but it would be such a hassle to copy and update the starter kit files every time there’s an update needs to be pushed from the core platform team and it isn’t restrictive enough because each team can still change the code on several places that should be framework level codes to make their code “just works”.</p><p>We could also build a single monolithic app and let each team contribute to the app, but then, we’ll be going back to square one and produce another monolith that’s hard to release and even worse, there’s a high chance that an error on some module that’s unrelated to your module can cause your module or even the whole application to break, because you know, SPA and stuff.</p><p>With these considerations in mind, Treats were built to be a framework that:</p><ol><li>Provide users with list of curated essential dependencies to kickstart their projects such as i18n, state management, graphQL client, head tag management and build tools.</li><li>Can work with zero configuration but flexible enough for power users to configure their project to suits their needs.</li><li>Easily extensible and all non-basic functionalities should be loosely coupled from the core framework code.</li><li>Painless update — update should be as simple as bumping Treats dependency on user’s package.json.</li></ol><h3>Meet Treats (and its ecosystem)</h3><p>Treats itself officially consists of several different packages:</p><ol><li><a href="https://www.npmjs.com/package/treats">treats</a> — The framework itself, this package is the reason all the magics are possible.</li><li><a href="http://npmjs.com/package/create-treats-app">create-treats-app</a> — A simple <em>à la</em> <a href="https://github.com/facebook/create-react-app">create-react-app</a> code generator to help users kickstart their Treats project.</li><li><a href="https://www.npmjs.com/package/eslint-config-treats">eslint-config-treats</a> — An integrated Eslint config for Treats application development that extends <a href="https://www.npmjs.com/package/eslint-config-airbnb">Airbnb</a> and <a href="https://www.npmjs.com/package/eslint-config-prettier">Prettier</a> style guide.</li><li><a href="https://www.npmjs.com/package/stylelint-config-treats">stylelint-config-treats</a> — A Stylelint config for Treats application development.</li><li><a href="https://www.npmjs.com/package/@treats/addons-base">@treats/addons-base</a> — Official Treats add-ons package that we recommends.</li></ol><h4>Get started with Treats</h4><p>Okay, let’s get started with Treats! To kickstart your Treats project, we recommend create-treats-app:</p><pre>$ npm install -g create-treats-app<br>$ create-treats-app<br>$ cd /YOUR/APP/DIRECTORY<br>$ yarn start</pre><p>Here’s the directory that you would find when you first created a new Treats project:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/331/1*XyG0k8dcNu52BDZy_uAc9g.png" /><figcaption>Initial Treats Project Structure</figcaption></figure><p>Usually all your codes would live under the src directory. There, you’ll see several directories, one of them are _route directory with module.js and route.js file under it. They can be used to register your page and its routing configuration, they’re a perfect example of filesystem hooks. Treats uses filesystem hooks as user’s API to extends its core implementation. By convention, all of these filesystem hooks should live under directories that’s prefixed with _. There’s many other filesystem hooks that you could provide to extend Treats. We’ve already covered about what filesystem hooks are available in Treats on <a href="https://tokopedia.github.io/treats/docs/api-reference/filesystem-hooks.html">Filesystem Hooks</a> section of Treats documentation.</p><p>treats.config.js file can be used to modify Treats build configuration. With this file, you can add aliases, extending Treats Webpack, Babel, Jest and PostCSS configuration, so you wouldn’t stuck with the default build tools setup.</p><h4><strong>Core Features</strong></h4><p><strong>Server-side rendering</strong></p><p>Treats are fully server-side rendered by default, to populate your component’s data you can use getInitialState from your root page component to fetch or populate your component’s data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*-jb3omQBakmwfOWtdKPLqw.png" /><figcaption>Setting getInitialState for root page component</figcaption></figure><p><strong>Code-splitting</strong></p><p>There’s a known “hardship” in React community when we’re talking about keeping code-splitting, hot-module replacement and server-side rendering cooperate together. But thanks to <a href="https://github.com/faceyspacey/react-universal-component">react-universal-component</a> and <a href="https://github.com/gaearon/react-hot-loader">react-hot-loader</a> that we use to build AsyncLoader and AsyncComponent we don’t have to worry about them anymore, all you need to do is wrap your code with these components and it’ll just work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*8mFHauq9tJBwhvG0gyvlZQ.png" /><figcaption>AsyncLoader that was build on top of react-universal-component act as the code-splitting entry for our async bundle</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*ZMriKR4AANmgvMke4AuX1A.png" /><figcaption>AsyncComponent that was build on top of react-hot-loader act as the hot-module-replacement enabler for our async bundler</figcaption></figure><p><strong>Localization</strong></p><p>Localization in Treats are using the popular <a href="https://github.com/yahoo/react-intl">react-intl</a> library under the hood. React-intl uses FormatJS syntax that we think is very straightforward to use to write translations, you should checkout their docs <a href="https://formatjs.io/">here</a>. We already do the setup for IntlProvider and other magical things that needs to be done when using react-intl, all you need to do is to fill up the translations according to your needs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*H75k__EHe5wMMArxWyDLng.png" /><figcaption>English version of our app will render this</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*O-lYa5oBm_Uxfi4PdKFAmA.png" /><figcaption>Indonesian version of our app will render this</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*-rkkCCXx9DBSkuSwHVpyww.png" /><figcaption>It’s time to use our translations!</figcaption></figure><p>We enabled English and Indonesian as the default language but feel free to adjust them to your needs. Want to adjust the language(s) ? Head on to the <a href="https://tokopedia.github.io/treats/docs/main-concept/localization.html">Localization</a> section of Treats documentation.</p><p><strong>State management</strong></p><p><a href="https://redux.js.org/">Redux</a> is currently one of the most popular state-management for modern web apps and it is very popular among React community, that’s why we bundled Redux with Treats as one of our main way to do state-management (the other way is using <a href="https://www.npmjs.com/package/apollo-link-state">apollo-link-state</a> in conjunction with Apollo client directly without any other state-management library).</p><p>With Treats, you’ll only need to take care about your reducer and Redux middleware that you’ll use, all setup for redux provider, etc and all the hassle to hydrate your client-side redux had already been handled by us.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*ObGs3AFLegCgv6kC79LTcg.png" /><figcaption>What middleware(s) you want to use today, sir?</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*m8kHFNs5wbFun8SnUOLi-w.png" /><figcaption>Insert reducer to continue..</figcaption></figure><p>You might not need Redux in your application, if that’s the case then you can just not include Redux on your Treats build, you can do this by setting the build configuration for Redux on treats.config.js to false like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*hy9KUhNCb1ndz6qbSkQawA.png" /><figcaption>Boom! All those Redux codes just got nuked!</figcaption></figure><p><strong>GraphQL client</strong></p><p>In short, <a href="https://graphql.org/">GraphQL</a> is a query language that let you define what datas that you need and only fetch those datas that you’ve defined in your query, GraphQL usually sits on a single endpoint that aggregates multiple APIs behind it so clients doesn’t have to know the implementation behind it, clients should only care about how it interact with the GraphQL endpoint itself.</p><p>To interact with GraphQL endpoints, we can either build our own GraphQL client with plain POST request or use several that’s already available on the market. In Treats, we use <a href="https://www.apollographql.com/">Apollo</a> as our GraphQL client of choice. Instead of providing tons of configuration that we usually provide when using Apollo client, we can just use 2 filesystem hooks (or less) if we didn’t need to alter the default configuration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*TuS81WQXSL1Od6ddIHnATA.png" /><figcaption>Inject your GraphQL endpoint URL</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*iRZxYKLZaHoZ8u5BWjywVA.png" /><figcaption>Do you need apollo-link-state resolvers? Then add them here! It’s fine if you don’t tho!</figcaption></figure><p>To use our GraphQL queries on React components, we could just import any <a href="https://github.com/apollographql/react-apollo">react-apollo</a>’s component from @treats/graphql :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*5RCmKjTRzAps1w0dBaXyRQ.png" /><figcaption>Witness the magic of Apollo GraphQL!</figcaption></figure><p>But wait! power users might want to build their own Apollo configuration, how can they do that? Fret not! We’re going to use yet another filesystem hook to do that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*x25UXQJWxk8SRn1MiljKfA.png" /><figcaption>Power users, hang on tight! custom configuration to the rescue!</figcaption></figure><p>To make creating Apollo links easier, we provided Apollo links generator that’s already packed with several built-in links, the detail of these built-in links can be found on the <a href="https://tokopedia.github.io/treats/docs/main-concept/graphql-client.html">documentation</a>.</p><p>Just like Redux, if you didn’t want to use GraphQL client, you could make its code goes away by setting the build configuration for it to false:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*voGHJhwaibxPpEGoWpjqIg.png" /><figcaption>GraphQL client codes just got nuked!</figcaption></figure><p><strong>CSS framework</strong></p><p>With Treats, you’re not stuck with single CSS framework implementation. We supported CSS modules with plain CSS, SASS and LESS out-of-the-box. For SASS and LESS users, all you need to do is just install the binary for CSS framework that you’ll use (<a href="https://github.com/sass/node-sass">node-sass</a> or <a href="https://www.npmjs.com/package/less">less</a>) and it’ll just works. We also supported CSS-in-JS framework usage by providing simple API to extends Treats server-side rendering functionality. You could take a look at our <a href="https://github.com/tokopedia/treats/tree/master/example">examples</a> on Treats repository for more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*iOaE7SRApvu2XCf0mbx-Sg.png" /><figcaption>Choose your flavor, or mix them maybe?</figcaption></figure><p><strong>Unit testing</strong></p><p>Treats bundled <a href="https://jestjs.io/">Jest</a>+<a href="https://airbnb.io/enzyme/">Enzyme</a> as the main testing framework, we’ve also provided several utilities from Enzyme as global function that can be called from your test files like shallow, mount and render. To make testing with react-intl easier, we also provided shallowWithIntl, mountWithIntl and renderWithIntl that automatically integrates with Treats react-intl implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*TtNcJZ5kzMOYz9l2C6od4A.png" /><figcaption>Unit test your code or it didn’t work!</figcaption></figure><p>To ran the unit tests, you can use treats test. Under the hood, treats test command would call our pre-configured Jest, so all Jest CLI options should work with it, for example:</p><pre>$ treats test --watchAll --clearCache</pre><p>By default, we provided a built-in integrated configuration for Jest, but you could also extend our default configuration with treats.config.js :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*TDtwUp7omJa3lhDKced8Ew.png" /><figcaption>Lemme teach you how to test!</figcaption></figure><p><strong>Code generator</strong></p><p>As lazy coder ourselves, we found out that in the process of developing a React app, there’s so much boilerplate codes that we need to wrote before actually writing our essential business logics. That’s why we included a simple code generator that eliminates this unnecessary process. To use code generator:</p><pre>$ treats generate &lt;GENERATOR_NAME|PATH_TO_TEMPLATE_DIRECTORY&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*BOw2e5XHE_bp3RJuFkuI6A.gif" /><figcaption>[GIF] Ain’t nobody got time to wrote those boilerplate codes!</figcaption></figure><p>There’s several built-in generator template in Treats that you can use:</p><ol><li>component — Generates React component boilerplates.</li><li>redux — Generates Redux boilerplates (action creator, reducer, thunks, etc).</li><li>test — Generates Jest test boilerplates.</li><li>helper — Generates Treats helper object boilerplates.</li><li>middleware — Generates Treats middleware object boilerplates.</li></ol><p>You can also build your own generator template to speed up your workflow. Head on to <a href="https://tokopedia.github.io/treats/docs/authoring-addons/generator.html">Building Your Own Generator</a> section of Treats documentation for more.</p><h4>Advanced Features</h4><p><strong>Helper and middleware</strong></p><p>To extend Treats server-side functionality, we could use helper and middleware.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*BcCQa7UZqz3EbFnsCWnAqw.png" /><figcaption>Relationship of Treats, helper and middleware when serving a request</figcaption></figure><p>Middleware are functions that sits between request/response cycle that allows for interjection of code between the cycle. Request and response context are passed on to each middleware calls, that’s why middleware are usually useful if we want to add/modify data that would be passed on to our React components as props, GraphQL clients, etc at the end of the request cycle. Example of a middleware: localization middleware, login middleware, etc.</p><p>To provide middleware and Treats with additional functionalities, we could use helpers to act as bridges/adapter to interact with external systems, implementations, etc. For example: Redis client, Database client, Circuit-breaker instances etc.</p><p>To learn more about helper and middleware, head on to <a href="https://tokopedia.github.io/treats/docs/main-concept/helper.html">helper</a> and <a href="https://tokopedia.github.io/treats/docs/main-concept/middleware.html">middleware</a> section of the docs.</p><p><strong>Add-ons System</strong></p><p>To make the capabilities and customizability of Treats limitless but keeping the core framework itself not too bloated, we could extend Treats functionality with add-ons. Add-ons can consist of helper, middleware, components and/or generator template. Since all compilation happens inside Treats internal, add-ons author doesn’t have to compile their codes with Webpack, Rollup, etc. They can be shipped as is under an NPM package. We recommends to ship your Treats add-ons under @treats scoped NPM package to make browsing for Treats add-ons easier. We’ve also covered about building simple add-ons on the <a href="https://tokopedia.github.io/treats/docs/authoring-addons/overview.html">documentation</a>, feel free to check it out!</p><p><em>PS: For more advanced usages, power-ups and gotchas, don’t forget to go to Treats </em><a href="https://tokopedia.github.io/treats"><em>documentation</em></a><em>!</em></p><h3>Conclusion</h3><p>It turns out that having our own home-grown React framework was good for our frontend-engineering agility, when we first migrated our Perl codes to React, it would take weeks just to modify, adjust or build boilerplate codes to suit our needs. Using Treats, it’ll only take couple of minutes to setup the configuration and then you could deploy it within another couple of minutes. We even have our own version of create-treats-app that generates all boilerplates for our common server config, deployment scripts, etc. With Treats, deployment, error handling and monitoring also became more predictable, since we’re having the same basic building blocks, whenever we encounter a problem, we could discuss the solutions across teams rather than trying to figure it out by ourself.</p><h4>The Make it Better 2.0</h4><p>Make it better had always been one of our DNA as Nakama at Tokopedia. Whilst Treats had already been used to sped up frontend engineering process at Tokopedia, Treats itself are still under very active development, so there’s still so much improvements that could be done with it.</p><p>For example, right now, we’re currently working on how to make all applications that’s built on top of Treats can be shipped separately on the background, but it can be combined on the client-side to form a single page application that just works (or if you’re into some gimmick jargons, you could call it <em>micro-frontend</em> 😏). We believe this improvement are a win-win solution for both engineers and users at Tokopedia, because we’re allowing ourself to ship code with agility without sacrificing user experience on the surface.</p><p>So what’s next? Treats with VueJS or Angular? combining generated static site page and fully SSR-ed web app into one single page application? making unicorns out of stardusts? 🤔 Well, let’s keep those wild imaginations flowing! Since we’re also inviting you to make Treats better with us! You could look at our list of <a href="https://github.com/tokopedia/treats/issues">Github issues</a> or please suggest one if you’ve any improvement ideas. If you have some difficulties while building your stuff with Treats, please don’t hesitate to report it too. If you’re more on to creating your own Treats add-ons, that would also be great, but please don’t forget to let us know, since we’re always keen to see what people build with our technologies!</p><p>And if you’re interested in democratizing commerce in Indonesia through technologies and always looking forward towards bigger and bigger problem to solve it and make things better while building great products like Treats, checkout <a href="https://www.tokopedia.com/careers/function/technology/">our careers page</a>! Let’s make it happen make it better together! Ciao!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a13c81f2738b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tokopedia-engineering/a-christmas-treats-for-you-a13c81f2738b">A Christmas Treats for you!</a> was originally published in <a href="https://medium.com/tokopedia-engineering">Tokopedia Engineering</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 better manage your React components with Storybook]]></title>
            <link>https://medium.com/@regalius/how-to-better-manage-your-react-components-with-storybook-c6b06abe71e9?source=rss-8e427cea571f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6b06abe71e9</guid>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Felix Tan]]></dc:creator>
            <pubDate>Sun, 29 Apr 2018 10:32:51 GMT</pubDate>
            <atom:updated>2018-04-29T10:47:20.345Z</atom:updated>
            <content:encoded><![CDATA[<p>Overview: I was very excited when I read the <a href="https://medium.com/storybookjs/announcing-storybook-3-4-db4d1341dedd">release announcement for Storybook 3.4</a> last week, so I decided to wrote an article about Storybook. Throughout this article, we’ll look at how we can create a better React project with Storybook and play with some addons that Storybook offers, we’ll also integrate Storyshots on our workflow so we can get both structural and image snapshots for better UI Regression Test. <a href="https://github.com/regalius/storybook-example">Demo</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PWD1BvdbfMAbdDg3eLUe0g.jpeg" /><figcaption>React + Storybook = Love — Photo courtesy of <a href="http://www.leahkelleyphotography.com/?ref=pexels">Leah Kelley</a> from Pexels with few programmer’s art edit of my own.</figcaption></figure><p>When you’re working on a React project, usually you’ll define reusable parts of your application in the form of components. There might come a time when your React project’s size snowballed and grown out of control to the point that you or your team members don’t even know how a component looks like, or maybe your team member created another <strong>Button</strong> component just because he/she doesn’t know if somebody already created it before. These are the obvious signs that you might need Storybook in your project.</p><p>So, what is Storybook and why should we use it? According to <a href="https://storybook.js.org/">Storybook</a>’s own definition, it is an UI development environment that you’ll love to use <em>(I do love to use it, I think you should too!)</em>. Storybook allows you to browse components inside a project, tinker with its state and interactively develop and test it. It runs outside of your application’s scope so you can develop your components without worrying about application dependencies, so if your designer wants to change a button’s color from red to blue, instead of worrying about some errors in your apps because of your drunk commits last night, he/she could just run the storybook and change the component directly.</p><p>Storybook supported several front-end frameworks out of the box, major front-end frameworks like <a href="https://reactjs.org/">React</a>, <a href="https://facebook.github.io/react-native/">React Native</a>, <a href="https://angular.io/">Angular</a> and <a href="https://vuejs.org/">Vue</a> (<em>finally we agreed on something, Angular and Vue folks!</em>) are already supported for quite some time, in the latest release they also added supports for <a href="https://www.polymer-project.org/">Polymer</a>.</p><h4>Installing Storybook</h4><p>The first obvious step to work with Storybook is to install it. To simplify setting up process, Storybook team had created a CLI tool to integrate Storybook into an existing project, you can install this tool globally with the following command:</p><pre>yarn global add @storybook/cli</pre><p>or if you prefer to use npm instead of yarn:</p><pre>npm i -g @storybook/cli</pre><p>After the installation step finished, go to your React project and simply run getstorybook:</p><pre>cd my-react-project<br>getstorybook</pre><p>The Storybook CLI will then cleverly determine your project’s architecture and then install Storybook according to the project’s need, so it doesn’t matter if you’re using create-react-app or just plain webpack, all you need to install Storybook is just this easy single command!</p><p>Next, you’ll want to make sure that Storybook had been installed properly, to do this, you can just simply run:</p><pre>yarn run storybook</pre><p>and navigate to <a href="http://localhost:9009/">http://localhost:9009/</a>, you’ll see this if Storybook had been installed properly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xZTzQ5FvRqRa8eOo6U2s6Q.png" /><figcaption>Storybook Welcome Screen, Congrats, you’re the chosen one!</figcaption></figure><h4>Customizing Storybook installation</h4><p>All Storybook configuration for your project will reside in .storybook directory, you’ll find this directory on your project’s root directory. There’s several files that can be used to customize your storybook installation:</p><ul><li><strong>config.js </strong>— In this file you can customize configuration for your Storybook installation.</li><li><strong>addons.js</strong> — You can register Storybook addons with this file.</li><li><strong>preview-head.html</strong> — You can use this file if you want to inject tags on your storybook <strong>head</strong> tag, this file can be useful if you have external scripts, css files, or maybe fonts that need to be injected and not bundled inside your app.</li><li><strong>webpack.config.js</strong> — Storybook automatically use their own webpack configuration by default, you can extend their webpack default configuration with this file if, for example, you need different webpack loader for your project. More information about customizing webpack configuration for Storybook can be found <a href="https://storybook.js.org/configurations/custom-webpack-config/">here</a>.</li><li><strong>.babelrc</strong> — By default, Storybook load .babelrc from project’s root directory, if you need to exclude some rules for Storybook environment, you can provide this file so only rules from this file will be loaded by Storybook.</li></ul><p>From my own personal preferences, I usually wants my story files to resides beside their related React component files, so instead of having a single big stories/ directory, I would put it like this:</p><pre>components/<br>    button/<br>       button.js<br>       button.stories.js<br>       button.css</pre><p>To do this, we need to change config.js loadStories function from this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3adb9b1158b20e69e155f729109369b4/href">https://medium.com/media/3adb9b1158b20e69e155f729109369b4/href</a></iframe><p>to this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef64c66a28c428bb792d8e1cd074159a/href">https://medium.com/media/ef64c66a28c428bb792d8e1cd074159a/href</a></iframe><p>In the example above, we used Webpack’s require.context to load all files that ends with .stories.js, so when we added a new story file, we wouldn’t have to specify it over and over again.</p><h4>Writing our first story</h4><p>Enough with the configuration, let’s write our first story. In this example, we’ll use the project from my previous post on <a href="https://medium.com/@felixtan/writing-reusable-redux-like-a-boss-d3780e7ecbf0">Writing Reusable Redux Like a Boss</a>. The reason we’re using that project is to better demonstrate how we can develop our UI component without even touching the business logics that had already been there a̶n̶d̶̶ ̶I̶’̶m̶ ̶t̶o̶o̶ ̶l̶a̶z̶y̶ ̶t̶o̶ ̶w̶r̶i̶t̶e̶ ̶a̶n̶o̶t̶h̶e̶r̶ ̶e̶x̶a̶m̶p̶l̶e̶.</p><p>For this example, we’ll write a story for Courses Widget Component:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*spVGxkI8NtBzD3VJXN_bBw.png" /><figcaption>The Courses Widget Component</figcaption></figure><p>The Courses Widget Component is responsible for displaying a list of courses that users can enroll on our React News site, it receives an array of courses and renders them.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/79ea8d83f2897285eb8bed1179ee248b/href">https://medium.com/media/79ea8d83f2897285eb8bed1179ee248b/href</a></iframe><p>To create a story, we simply import storiesOf from@storybook/react and then add each of our story entries like the above example. You can then run again your Storybook, and you’ll see the story right away:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iZLmMI5h3ZqmaS-oBlQz8Q.png" /><figcaption>The Courses Widget Stories entry.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ImyfCSHTJ2zCSK5jS9Khww.png" /><figcaption>The Courses Widget Item Stories entry.</figcaption></figure><p>To better documents our Courses Widget component, we wants to tell everyone who see this story if our enroll button can actually be clicked. Right now if you click the enroll button, nothing happens, we’ll change that with our first addon.</p><h4>Installing our first Addon</h4><p>Installing addons for Storybook is also quite simple, for our first addon, we’ll add <a href="https://github.com/storybooks/storybook/tree/master/addons/actions">action</a> addon. To do this, first we need to install it with yarn:</p><pre>yarn add --dev @storybook/addon-actions</pre><p>or npm:</p><pre>npm i -D @storybook/addon-actions</pre><p>We usually wants to install storybook addons in devDependencies, so we won’t pollute our production dependencies, after all, we don’t need it in our production builds. After we’ve finished installing the addons, we need to register it so that Storybook can use it later on, to register our addons, we can simply import it inside our addons.js file in .storybook directory:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/79221e4260b95e132481d26daa722ecf/href">https://medium.com/media/79221e4260b95e132481d26daa722ecf/href</a></iframe><p>We can then define the actions inside our courses-widget.stories.js:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/860016970289bd3fb8318488efe6217f/href">https://medium.com/media/860016970289bd3fb8318488efe6217f/href</a></iframe><p>Now, when you click the Enroll Button, it will log an action inside the action logger:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*5TRgReZo9TPp1ySD2-keXA.png" /><figcaption>The Action Logger Output</figcaption></figure><p>If you click the enroll button and it doesn’t responds with anything, you’ll know that something had gone wrong and it explains why those eager minds can’t enroll to our courses in the past few days.</p><h4>Generate a simple documentation with Info addon</h4><p>We’ve created a component library with Storybook, might as well wrote the documentation inside it, <em>eh?. </em>Well, we can auto-generate a documentation with <a href="https://github.com/storybooks/storybook/tree/master/addons/info">info</a> addon:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*iw6kHxOLIoGzPCtVkEesRg.png" /><figcaption>Example documentation from our Courses Widget with Info addon</figcaption></figure><p>First install it with:</p><pre>yarn add --dev @storybook/addon-info</pre><p>To better suits our need, we’ll do a few setups inside config.js:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a761c675d313cbd48c97f09c6e197af4/href">https://medium.com/media/a761c675d313cbd48c97f09c6e197af4/href</a></iframe><p>Since Info addon integrates well with <a href="https://github.com/reactjs/react-docgen">react-docgen</a> out of the box, to generate prop types table, we could use prop-types or if you wanted more advanced use-cases you could use flow, what they do is basically typecheck your prop data types so it can only be used for single data type throughout the entire life of your application. I could write about static typechecking and why they’re awesome here, but let’s keep it for another day, for now all you need to do is to install Flow with the following commands:</p><pre>yarn add --dev flow-bin<br>yarn run flow init</pre><p>We’ll then needs to define the flow types in our Courses Widget Component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a36f48159776324551eb91630c530890/href">https://medium.com/media/a36f48159776324551eb91630c530890/href</a></iframe><p>Then, in our Course Widget Component story file, we’ll add a new story entry wrapped with withInfo function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/98c4a2f640220f855b98347c302444d1/href">https://medium.com/media/98c4a2f640220f855b98347c302444d1/href</a></iframe><h4>Snapshot testing with Storyshots</h4><p>Storyshots allows us to automatically add snapshot testing with Storybook. With Storyshots, we don’t need to specify another snapshot tests in our testing framework like Jest, we simply use our stories that we’ve created previously. To use Storyshots, first, we’ll install it with:</p><pre>yarn add --dev @storybook/addon-storyshots</pre><p>We can then simply add a new test file inside our ./src directory to initialize Storyshots:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e876457f77e196c386226e3970a2f45/href">https://medium.com/media/2e876457f77e196c386226e3970a2f45/href</a></iframe><p>If we run our test suites with yarn run test we can see our snapshots generated in each of our component’s directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*__bMriRhEP8vKRMgoSz1vQ.png" /><figcaption>The snapshot had been successfully generated inside our Courses Widget Component directory</figcaption></figure><p>Now when you change the structure of your component, you’ll get a warning that something had changed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*-prwOlRLjsUM6ZK21Y_ckw.png" /><figcaption>Something had changed, is this what you want or are you just drunk bruh?</figcaption></figure><p>When those changes are expected, you can just simply press u to update failing snapshots, or press i to interactively update the failing snapshots.</p><p>With structural snapshot testing, we can compare how component’s structure looks like and we can do regression tests based on it. But it can’t cover changes that might happens visually, for example if you or your team members changed some CSS rules and alter the component’s visual, you can’t catch that regression with just structural regression test.</p><p>Luckily in Storybook 3.4, aside from using our stories to do structural snapshot testing, we could use it also in visual snapshot testing. to do this, we can just simply initialize another Storyshots suite:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f0f164fd87c150f4315d1ef2b18433aa/href">https://medium.com/media/f0f164fd87c150f4315d1ef2b18433aa/href</a></iframe><p>What Storyshots do in image snapshot testing is basically navigate to given Storybook URL with a headless browser (<a href="https://github.com/GoogleChrome/puppeteer">puppeteer</a>), capture screenshots of each of our stories and save it as images to do visual regression tests later on. Visual regression tests can then be conducted with the help of <a href="https://github.com/americanexpress/jest-image-snapshot">jest-image-snapshot</a>. So, to be able to get our image snapshot testing running, we need to start our Storybook instance first with yarn storybook, or build a static one with yarn build-storybook.</p><p>Rather than running two scripts each time we want to run our test suites, we can use <a href="https://www.npmjs.com/package/npm-run-all">npm-run-all</a> to run it all at once and <a href="https://www.npmjs.com/package/wait-port">wait-port</a> to wait for the Storybook to be ready to handle the request. Let’s install npm-run-all and wait-port with:</p><pre>yarn add --dev npm-run-all wait-port</pre><p>Then in package.json we can create a new script to run it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1fa8f01986e24676d088c2cbe40aed2/href">https://medium.com/media/f1fa8f01986e24676d088c2cbe40aed2/href</a></iframe><p>Now we can run our tests with yarn test:watch. When you ran the tests again, you’ll see that image snapshots had been successfully generated inside __image_snapshots__ directory:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oSzvw_00AIUn-8rfKiOYBg.png" /><figcaption>Image snapshot successfully generated.</figcaption></figure><p>When you change some CSS rules, Jest will throw a warning that the visual regression failed, and asks if it was expected or not:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XN0PTSOSunUvzILvaNP_gg.png" /><figcaption>Now the visual changed, is it expected? Plz check the image file for more info</figcaption></figure><p>We can then check the difference in the diff file that was generated:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7fJUIr2l6eZ1cpY57TphwQ.png" /><figcaption>Whoops! We accidentally change our button’s color from React-ish Blue to Angular-ish Red, this is blasphemy for sure!</figcaption></figure><p>With visual snapshot testing, we can make ourself sure that we kept our visual changes in control, instead of checking each component’s manually, we kept the boring job for our testing framework.</p><p>So far I’ve been happy with the results, but there’s two issues that can be fixed here:</p><ol><li>We don’t want to do snapshot tests to our Read Me files, since it is intended only for documentation purpose, it will be cumbersome to update the snapshots each time we update our Read Me files.</li><li>We want to keep our image snapshots file relative to its related components.</li></ol><p>For the first issue, we can wrap our Read Me story with a simple NODE_ENV checking:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/01ede61b96da68a06b4554d063c6b071/href">https://medium.com/media/01ede61b96da68a06b4554d063c6b071/href</a></iframe><p>For the second issue, since StoryShots image snapshot uses jest-image-snapshot internally, we could pass a simple configuration by adding getMatchOptions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ac874159b4361e540f3307366d3f645/href">https://medium.com/media/6ac874159b4361e540f3307366d3f645/href</a></iframe><p>There are other configurations that we can pass to jest-image-snapshot like Failure Threshold, etc. You can find this list of configuration in jest-image-snapshot <a href="https://github.com/americanexpress/jest-image-snapshot#optional-configuration">documentation</a>.</p><p>In Continuous Integration (CI) environment, you might want to make sure that Storybook had been ready before doing the regression tests, I usually prefer to use static build Storybook in CI environment. To do this, we’ll introduce a new environment variable with cross-env:</p><pre>yarn add cross-env</pre><p>Then in our package.json we need to make new scripts to be ran on CI environment:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f903edb44cb7335f40900713e3226cdc/href">https://medium.com/media/f903edb44cb7335f40900713e3226cdc/href</a></iframe><p>Setting CI environment variable to true will make create-react-app to run Jest in non-interactive mode, moreover we can use this environment variable to change our Storybook URL in Storyshots to point at the static built Storybook:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c98e2fc8a6ecd039bcbd11f18b3c2e88/href">https://medium.com/media/c98e2fc8a6ecd039bcbd11f18b3c2e88/href</a></iframe><h4><strong>Other useful addons</strong></h4><p>I generally loves all the addons that Storybook offers, but there’s few that I personally use:</p><ol><li><a href="https://github.com/storybooks/storybook/tree/master/addons/knobs">Knobs</a> — with this addon we can interactively tinker our component’s props to see what happens to it on different props.</li><li><a href="https://github.com/storybooks/storybook/tree/master/addons/jest">Jest</a> — Jest addon will show your Jest test results directly on your component’s Storybook entry.</li><li><a href="https://github.com/storybooks/storybook/tree/master/addons/viewport">Viewport</a> — this addon can help us see the responsiveness of our components at different viewport sizes.</li><li><a href="https://github.com/storybooks/storybook/tree/master/addons/graphql">GraphQL</a> — this addon can be used to display <a href="https://github.com/graphql/graphiql">graphiQL</a> IDE with example queries inside Storybook.</li><li><a href="https://github.com/truffls/storybook-addon-intl">Intl</a> — this addon provide switcher for <a href="https://github.com/yahoo/react-intl/wiki/Components">react-intl</a> locale, since react-intl is my i18n framework preferences, this addon is a must for me.</li></ol><h4>Conclusion</h4><p>With Storybook you can easily browse, manage and test your React components library. Working on a big scale project with many different team members across different functionality is hard. Let’s hope that by adding another set of tools under our sleeves, it might ease up our life a little bit.</p><p>Thanks for reading, also don’t forget to checkout the <a href="https://github.com/regalius/storybook-example">demo repository</a>. And as always, <strong>Happy Hacking</strong>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6b06abe71e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing Reusable Redux Like a Boss]]></title>
            <link>https://medium.com/@regalius/writing-reusable-redux-like-a-boss-d3780e7ecbf0?source=rss-8e427cea571f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3780e7ecbf0</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Felix Tan]]></dc:creator>
            <pubDate>Sun, 15 Apr 2018 09:48:58 GMT</pubDate>
            <atom:updated>2018-04-15T14:41:32.249Z</atom:updated>
            <content:encoded><![CDATA[<p>Overview: In this article, we’ll try to ease ourself from both physical and emotional pain on rewriting the same Redux logics over and over again in our application with Generator and Selector pattern. You can see the example implementation here: <a href="https://github.com/regalius/reusable-redux">DEMO</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PamT-j__lthGY5XRlYFeTQ.jpeg" /><figcaption>I’mma sleep here while you’re repeatedly rewriting the same redux logics over and over again</figcaption></figure><p>If you’re Javascript hipsters like myself, chances are you won’t miss the hype of <a href="https://reactjs.org/">React</a> and its ecosystem in the past few years. React and its tagline <em>Learn once, Write Anywhere </em>allows JS developers to declaratively build their user interfaces in not just on the Web, but also <a href="https://facebook.github.io/react-native/">Mobile apps</a> and also <a href="https://facebook.github.io/react-vr/">Virtual Reality</a>. When talking about React apps, there’s one thing that you can’t possibly miss. Yep, you guessed it, it’s <a href="https://redux.js.org/">Redux</a>!</p><h4>Redux Key Principles</h4><p>Redux offers a simple way to separate and manage our app’s states so those states won’t ended up cluttering our UI codes like in good ol’ jQuery days. To do this, redux introduces three basic principles that composes the whole Redux ecosystem:</p><p><a href="https://redux.js.org/basics/actions"><strong>Actions</strong></a><strong> — </strong>The payloads that used by our application to interact with Redux. Actions are the only source of information that can get in to our store. To create actions, usually we use an <strong>Action Creators</strong>, they’re basically a function that receives input and produces actions based on the given input.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*mwthgfJT_r9IiAQ7WMoZ-g.png" /><figcaption>The Action Creators</figcaption></figure><p><a href="https://redux.js.org/basics/reducers"><strong>Reducers</strong></a> — Reducers are a function that acts as sets of rules that tell our Store how it should react to actions that are passed on to them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*2Os1FOKgMXp4GIio8IQt0Q.png" /><figcaption>The Reducers</figcaption></figure><p><a href="https://redux.js.org/basics/store"><strong>Store</strong></a><strong> </strong>— The single object tree that holds the whole states in our application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*qG8G8rX2fHIijqZUPRoOPA.png" /><figcaption>The Store that wraps it all</figcaption></figure><p>It is acceptable to use simple implementations like above if we used every redux logics only once in a single part of our application, however, we’ll start to see code duplication if we wants to reuse the same logics in - <em>i.e. different pages in our application</em>. For example, let’s say we have a news app that wants to fetch different news in <strong>Home</strong> page and <strong>Newsfeed</strong> Page but uses the same logics, we might wrote it like this:</p><p><strong>Home Page</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd2e876d35191c1bf78c373318a11ecd/href">https://medium.com/media/dd2e876d35191c1bf78c373318a11ecd/href</a></iframe><p><strong>Newsfeed Page</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ab76313f6660b0e60767b45b6f9416e/href">https://medium.com/media/7ab76313f6660b0e60767b45b6f9416e/href</a></iframe><p>This requires us to rewrite the same code over and over again, and if there’s a future change on how we should handle the news data, we’ll have to find and change every pages that implements the same logics. Since we’re too lazy to do this, it is obvious for us to find a good solution to solve this dire problem.</p><h4>The Generators</h4><p>Since Redux key principles are just some plain functions that built on functional concepts, we can create simple generator functions to help us generate these objects for each usage/pages that needs to implement the same redux logics.</p><p>Our generator functions would receive the page’s name and implementation detail of the Redux principle that we’ll going to generate:</p><p><strong>Type Generator</strong></p><p>This generator function’s purpose is simple, append page’s name to action type string with delimiter of your choice, general convention uses / as redux page name delimiter, but you’re good to go with your personal preferences:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31cfc7f5e2236e379b83659a20e470f5/href">https://medium.com/media/31cfc7f5e2236e379b83659a20e470f5/href</a></iframe><p><strong>Action Creators Generator</strong></p><p>Action Creators Generator will help us generate the necessary action creators based on our page’s name.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a405e86bc2cbaeee41c63d0c693b95c/href">https://medium.com/media/4a405e86bc2cbaeee41c63d0c693b95c/href</a></iframe><p><strong>Action Handler Generator</strong></p><p>Action Handler Generator helps in generating action handlers object to be used by our reducer. What is action handler? I’ll explain it after this section.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80a26c89d79c9585a635590b5c45aa82/href">https://medium.com/media/80a26c89d79c9585a635590b5c45aa82/href</a></iframe><p><strong>Reducer Generator</strong></p><p>Reducer generator with the help of<strong> Action Handler Generator</strong> will help in generating the necessary reducer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4092626c27d4abda76807ac399683761/href">https://medium.com/media/4092626c27d4abda76807ac399683761/href</a></iframe><h4>Writing the common redux logics</h4><p>You might asks, then how are we supposed to get the generator working with our existing redux setup? Well, to be able to use the generators, we’ll need to change few things:</p><p><strong>Action Creator</strong></p><p>We’ll need to change our action creators to accept page’s name:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0433ff939042ea0115dd20304af4f0e0/href">https://medium.com/media/0433ff939042ea0115dd20304af4f0e0/href</a></iframe><p><strong>Reducer</strong></p><p>To transform our reducer into reusable reducers, first, we have to decouple the reducer and action handler:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f6d23b3efab3cc46b2bebc1db647e41/href">https://medium.com/media/6f6d23b3efab3cc46b2bebc1db647e41/href</a></iframe><p>What we’re doing in the above codes are actually the same with using reducer in <strong>switch</strong> form, we’ll match the action’s type with <strong>Action Handler </strong>object keys(in <strong>switch</strong>, this is the <strong>case</strong> part), if it isn’t found, then we simply returns the current state (in <strong>switch</strong>, this is the <strong>default</strong> part).</p><p>Finally after these two had been decoupled, we’ll implement them to use our reducer generator function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0350c2aab293d60adb003b7d86af5458/href">https://medium.com/media/0350c2aab293d60adb003b7d86af5458/href</a></iframe><h4>Using the common redux logics</h4><p>To use the common redux logics, we can simply call our generator functions, that’s it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c878534c98c60f4f7c9daee23e176753/href">https://medium.com/media/c878534c98c60f4f7c9daee23e176753/href</a></iframe><h4><strong>The Selectors</strong></h4><p>Common redux logics like above works well with Redux Selector pattern. In Redux Selector pattern, a selector function receives the whole redux state tree and slice or compute derived data from it to obtain data that is currently requested. In React and Redux setup, usually we’ll implement this pattern with the help of <a href="https://github.com/reactjs/reselect">reselect</a> library.</p><p>For this example, let’s pretend that we’ve just received a word from our product manager that he wants to separate the news section in <strong>Home</strong> page into different sections with the following requirements:</p><ol><li><strong>Editor’s Choice </strong>— We want this section to be filled with 6 latest featured news.</li><li><strong>Other News</strong> — This section will contains the other news that didn’t make it to the top 6.</li></ol><p>Instead of t̵h̵r̵e̵a̵t̵e̵n̵i̵n̵g̵ ̵a̵n̵d̵ ̵d̵e̵b̵a̵t̵i̵n̵g̵ asking our Back-end engineers to change their API response schema, we might be able to solve this problem with the help of selectors. First, we’ll create a selector for our common news redux:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b69db9783eaa53c4bbfd6e9f330a0252/href">https://medium.com/media/b69db9783eaa53c4bbfd6e9f330a0252/href</a></iframe><p>With above selector, we can abstract the implementation detail on how to select specific data from news redux state to its own selector. Then in our <strong>Home </strong>page, we can simply compose our <strong>Home</strong> selectors to use the news selector implementation to compute its derived data:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9609e57a8841c049f23e4aa439ae5b0e/href">https://medium.com/media/9609e57a8841c049f23e4aa439ae5b0e/href</a></iframe><p>With this pattern, if there’s any data structure or implementation detail changes, we’ll only need to change how we select our news data in news selector, if we need to change how we compute our data in <strong>Home</strong> page, then we’ll simply change how we select the data in our home selector, Simple!</p><h4>Using Selectors in React Component</h4><p>The last thing we need to do is to use our selectors on <strong>mapStateToProps</strong> function in our React Component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b31f2ab5e9c7423c7277c749d7b25d4/href">https://medium.com/media/5b31f2ab5e9c7423c7277c749d7b25d4/href</a></iframe><p>Well, that’s all you need to reuse your Redux logics.</p><p><strong>Happy Hacking!</strong> — And don’t forget to check the <a href="https://github.com/regalius/reusable-redux">DEMO</a> to better grasp the concept.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3780e7ecbf0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>