<?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[React Weekly - Medium]]></title>
        <description><![CDATA[A curation of the best React JS related content — http://www.reactweekly.co - Medium]]></description>
        <link>https://medium.com/react-weekly?source=rss----955bdba6e52f---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>React Weekly - Medium</title>
            <link>https://medium.com/react-weekly?source=rss----955bdba6e52f---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 14 Nov 2026 14:25:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/react-weekly" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Feature oriented architecture for web applications]]></title>
            <link>https://medium.com/react-weekly/feature-oriented-architecture-for-web-applications-2b48e358afb0?source=rss----955bdba6e52f---4</link>
            <guid isPermaLink="false">https://medium.com/p/2b48e358afb0</guid>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[rekit]]></category>
            <dc:creator><![CDATA[Nate Wang]]></dc:creator>
            <pubDate>Sun, 11 Sep 2022 22:09:05 GMT</pubDate>
            <atom:updated>2022-09-11T22:09:05.582Z</atom:updated>
            <content:encoded><![CDATA[<p>Feature is a very nature concept for people to understand a system. It’s also used to describe user requirements for software development. But when a feature comes to programmers side it’s usually immediately converted to technical artifacts such as components, actions, models etc. This convention adds the difficulty for new comers or developers themselves serval weeks later to understand the system.</p><p>So if we organize a web project by features rather than technique categories (like components, actions, models) it will help us always manage the project under control when the project grows because we construct the system with bigger units.</p><p>This architecture is also the key concept of <a href="https://github.com/supnate/rekit">Rekit</a>, a toolkit for building web applications with React, Redux and React router.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*U58Y3rouWd_uplY3GWe3Kg.png" /><figcaption><a href="https://github.com/supnate/rekit">https://github.com/supnate/rekit</a></figcaption></figure><p>Unlike backend system, frontend web application is the direct interface for user to understand the capabilities of an application. So it’s more suitable to be organized by features.</p><h4>What is a feature?</h4><p>At first let’s define what a feature means:</p><blockquote>A feature is some capability of a system.</blockquote><p>That is a feature always adds some functionality to a system. For example, For a content management system, a new supported content type is a feature, for an IDE the capability to run tests is a feature.</p><h4>Organize application by features</h4><p>For a complex web application, it’s usually hard to understand how different parts work together. Original developers need to draw architectures, write documents to describe the system so that other could understand. But maintaining them is very hard because when the project evolves docs don’t evolve themselves. People need to update them in time so that they won’t mislead while they don’t help. So how if the project itself is self-describle? A feature oriented architecture is helpful for this.</p><p>Because we’ve grouped components, actions, stores into features, we don’t need to think about how these small parts work together but we only consider how features work together to construct the whole application. Features are much bigger units than pure technical artifacts like components, actions or models. By analyzing dependencies between features the system could auto generate understandable and accurate diagrams for developers to learn or review the project.</p><h4>The implementation using React, Redux, React router</h4><p>The idea is developed by creating apps using React, Redux and React router. Here is the general architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3lSb1nwK8vEd2UMhW1opHA.png" /></figure><h4>Real word example</h4><p>Let’s compare below two diagrams, from <a href="https://github.com/supnate/rekit-portal">Rekit portal</a>, one contains relationship between small artifacts and the other only contains relationship between features. It’s obvious the first one is too complicated to understand. In fact, we usually don’t need to care about the complexity inside a feature because it’s small and it doesn’t prevent from understanding the whole application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*yr3ESCIJelhaJtaC3zZ7nQ.png" /><figcaption>All Dependencies Visible</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*n80w5i7qdd6cGAEK_YxLWw.png" /><figcaption>Only dependencies among features</figcaption></figure><p>By this approach, we separate concerns of a large project. Each feature is self manageable and decoupled from others. To understand the whole project, we look at relations among features, to understand we only look into a single and small feature.</p><h4>Hard and soft dependencies</h4><p>Since features need to work together, we can’t avoid dependencies among features. Actually a new feature is very possible to be based on other existing features. But we also should make feature more individual as much as possible. And we should avoid hard circular dependencies. Here we mention hard dependencies, oppositely we also have soft dependencies. Below is what we define hard and soft:</p><blockquote>When feature A is based on feature B, that is B will not work without A. We say the dependency from B to A is a hard dependency.</blockquote><p>For example, diagram feature provides visualization of the project, it uses data from home feature, if no home feature then diagram doesn’t work. Then we say diagram hardly depends on home.</p><blockquote>When feature A uses some artifacts from B (depends on B) to provide new capabilities, but if without B, A still works by simply remove related code. Then we say the dependency from A to B is a soft dependency.</blockquote><p>For example, in <a href="https://github.com/supnate/rekit-portal">Rekit portal</a> application, Rekit-cmds feature provides the ability to manage Rekit elements, but home feature needs to provide menu items as entries. Then we say home softly depends on Rekit-cmds feature. Soft dependencies usually could be dismissed by designing some extension mechanism. For example, if home feature allows other features to register menu items then there will be no dependencies from home to Rekit-cmds. However an extension architecture always adds much complexity to the system, if not heavily needed, we prefer soft dependencies so that the system is easier to understand or debug.</p><p>In Rekit portal diagrams, we can easily find hard in solid lines, and soft dependencies in dashed lines. See below, when mouse over Rekit cmds feature, we can see the hard and soft dependencies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rQN59zmDRdCFPPLE-nKPMQ.png" /><figcaption>Dependencies of Rekit cmds feature</figcaption></figure><h4>Conclusion</h4><p>This article describes the thought of building an application by features. All small technique artifacts should be grouped by features so that the whole system is scalable and maintainable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b48e358afb0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/react-weekly/feature-oriented-architecture-for-web-applications-2b48e358afb0">Feature oriented architecture for web applications</a> was originally published in <a href="https://medium.com/react-weekly">React Weekly</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Native and Typescript]]></title>
            <link>https://medium.com/react-weekly/react-native-and-typescript-ad57b7413ead?source=rss----955bdba6e52f---4</link>
            <guid isPermaLink="false">https://medium.com/p/ad57b7413ead</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Patricio López Juri]]></dc:creator>
            <pubDate>Sun, 18 Sep 2016 12:52:08 GMT</pubDate>
            <atom:updated>2017-05-01T18:59:52.990Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<h4>The main intention of this blog post is to show how to setup a React Native project with a Typescript environment as an alternative to Flow.</h4><p><strong>EDIT: This guide is outdated. Please go to the updated repository: </strong><a href="https://github.com/mrpatiwi/ReactNativeTS">https://github.com/mrpatiwi/ReactNativeTS</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*bkpDuXSJByrUmrBRkd26zg.png" /></figure><p>Go ahead and install <a href="https://nodejs.org/">Node.js</a> and the required tools from the official install guide: <a href="https://facebook.github.io/react-native/docs/getting-started.html#content">https://facebook.github.io/react-native/docs/getting-started.html#content</a></p><h4>A more complete example code and starting point is available here:</h4><p><a href="https://github.com/mrpatiwi/ReactNativeTS">mrpatiwi/ReactNativeTS</a></p><p>Up next, we will setup the most basic React Native application with Typescript.</p><h3>Environment</h3><p>The most adequate IDE is <a href="https://code.visualstudio.com/">Visual Studio Code</a>, this doesn’t means you can’t use your favorite IDE. Just make sure you have a Typescript-related plugin, like <a href="https://atom.io/packages/atom-typescript">atom-typescript</a> for <a href="https://atom.io/">Atom</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FP3RecILCxajfhtt8vO5-w.png" /><figcaption>Preview of the final result with Visual Studio Code</figcaption></figure><h3>Dependencies</h3><p>Along with <a href="https://facebook.github.io/react-native/docs/getting-started.html"><em>react-native-cli</em></a>, we will need:</p><ul><li>Typescript</li><li><a href="https://github.com/typings/typings">Typings</a></li><li><a href="https://palantir.github.io/tslint/">TSLint</a></li></ul><p>Install all the required dependencies with:</p><pre>npm install -g typescript tslint typings react-native-cli</pre><h3>Creating the app</h3><p>Starting a React Native app is very straightforward:</p><pre># Create app<br>react-native init ReactNativeTS</pre><pre># Navigate to the just created app<br>cd ReactNativeTS</pre><pre># Start git<br>git init</pre><p>It’s a good practice to have the Typescript-related dependencies at the <em>package.json </em>file, so:</p><pre>npm install --save-dev typescript tslint typings</pre><p>To start a Typescript project and avoid long commands on the terminal, it’s good to have a <a href="https://www.typescriptlang.org/docs/handbook/tsconfig-json.html"><em>tsconfig.json</em></a> file.</p><p>Also, we need to keep track of the required typings, because they are not always bundled in the dependency itself, we will use <a href="https://github.com/typings/typings">Typings</a>:</p><pre>tsc --init<br>typings init</pre><p>The default config files should look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c931cce20fb83156855ff5c8411105f0/href">https://medium.com/media/c931cce20fb83156855ff5c8411105f0/href</a></iframe><h4><a href="https://github.com/typings/typings">Typings</a></h4><p>Let’s find the typings of React Native. We can use the <em>cli</em> as follow:</p><pre>typings search react-native</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CCvBd5DqwxgAK1JipZHvGg.png" /></figure><p>So, we found some typings, but they are written for <a href="https://github.com/DefinitelyTyped/tsd"><em>DefinitelyTyped</em></a>. To install them with <em>Typings</em> and move forward with the <em>React</em> typings we run:</p><pre>typings install dt~react dt~react-native --save --global</pre><p>The <em>dt </em>keyword has the meaning of telling the <em>cli</em> to use the definitions from <a href="https://github.com/DefinitelyTyped/tsd"><em>DefinitelyTyped</em></a>. The <em>global</em> flag is required for this cases.</p><h4>Typescript config</h4><p>Time to setup out <a href="https://www.typescriptlang.org/docs/handbook/tsconfig-json.html"><em>tsconfig.json</em></a> file. Here are declared all the required info to tell Typescript transpiler how to build our app. We will use the following settings:</p><ul><li>Our target <em>JS</em> will be <strong><em>ES2015</em></strong>, because React Native supports it by default. Also we want to use <strong><em>JSX</em></strong> syntax and be able to include Javascript files along with Typescript files.</li><li>Out source code will be located at <strong><em>src</em></strong> directory and the output JS files will be placed at the <strong><em>build</em></strong> directory.</li><li>We want to follow as much as possible the <a href="https://babeljs.io/docs/learn-es2015/#Modules"><strong><em>Babel</em> import system</strong></a>. That’s why we will activate <a href="https://www.typescriptlang.org/docs/handbook/compiler-options.html"><em>allowSyntheticDefaultImports</em></a><em>.</em></li></ul><p>The recommended <em>tsconfig.json</em> file should be like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/15dce8ed94ee8756db571854e3a4f7e5/href">https://medium.com/media/15dce8ed94ee8756db571854e3a4f7e5/href</a></iframe><p>Don’t forget to add the following to your <em>.gitignore</em>:</p><pre># .gitignore<br>build<br>typings</pre><h4>Prepare React Native app</h4><p>To easily support Typescript, let’s create the main entrance of our app at the <em>src</em> directory:</p><pre>mkdir src<br>touch src/index.tsx</pre><p>As a minimal working example, our main component will be as next:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6b94752f24dee001313b068db47a137/href">https://medium.com/media/e6b94752f24dee001313b068db47a137/href</a></iframe><p>A few notes about this:</p><ul><li>We import <em>React</em> and <em>React Native</em> modules as always.</li><li>Our IDE should capable of showing autocomplete for types and show warnings and errors.</li><li>Component must have a <strong><em>State</em></strong> and <strong><em>Props</em></strong> interfaces. If empty, you can always use the <strong><em>any</em></strong> type.</li><li>The styles must have typings.</li></ul><p>To see how Typescript is transpiling our new components, run:</p><pre>tsc</pre><blockquote>This automatically reads the <em>tsconfig.json</em> file.</blockquote><p>The final JS file is placed at <em>build/index.js:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f6ieJngWosESP0frDUCBqA.png" /><figcaption>Transpiled Javascript file from Typescript source</figcaption></figure><p>You can see this is a common React Native Javascript file. The typings and <em>interfaces</em> are removed and the JSX syntax in converted to normal Javascript.</p><h3>Putting it all together</h3><p>Currently, the main index files:</p><ul><li><em>index.android.js</em></li><li><em>index.ios.js</em></li></ul><p>Are not pointing to our new base components. We should edit them as follow:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be1a0a44a8dbf9d22c8e7094fa425b75/href">https://medium.com/media/be1a0a44a8dbf9d22c8e7094fa425b75/href</a></iframe><p>This implies that we expect to have built the TS source before running the app on a device or emulator.</p><p>Also I recommend to have the following scripts in the <a href="https://docs.npmjs.com/files/package.json"><strong><em>package.json</em></strong></a> file:</p><pre>&quot;scripts&quot;: {<br>  &quot;preinstall&quot;: &quot;rm -rf typings&quot;,<br>  &quot;postinstall&quot;: &quot;node node_modules/typings/dist/bin.js install&quot;,<br>  &quot;start&quot;: &quot;node node_modules/react-native/local-cli/cli.js start&quot;,<br>  &quot;android&quot;: &quot;node node_modules/react-native/local-cli/cli.js run-android&quot;,<br>  &quot;ios&quot;: &quot;node node_modules/react-native/local-cli/cli.js run-ios&quot;,<br>  &quot;prebuild&quot;: &quot;rm -rf build&quot;,<br>  &quot;build&quot;: &quot;tsc&quot;<br>},</pre><p>Open two terminals and run:</p><pre># One terminal for build and watch for changes<br>npm run build -- --watch</pre><pre># Other terminal to run the development server<br>npm start</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*29_Tcrs_7OYqjrFYCN4hXw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*ZGGfbtVeCYtHXO0SufX-Hg.png" /></figure><h4>iOS &amp; Android</h4><p>Open another terminal (sorry!) to run it on a <strong>iOS </strong>emulator:</p><pre>npm run ios</pre><p>To run it on <strong>Android</strong>, be sure to follow the install instructions from:</p><p><a href="https://facebook.github.io/react-native/docs/getting-started.html#dependencies-for-android">https://facebook.github.io/react-native/docs/getting-started.html#dependencies-for-android</a></p><p><strong>Now, any change made to the contents of the <em>src</em> directory will update the JS files.</strong> So <em>Hot Reloading</em> must be working well right now.</p><p>To build the source without watching is simple as:</p><pre>npm run build</pre><h3>Adding custom components</h3><p>It’s all about components and it rich ecosystem available to developers. So I will show how to add third-party modules and make them work with Typescript. Because — <em>let’s be honest</em> — there should be none React Native components written in Typescript with typings.</p><p>As an example, let’s take:</p><p><a href="https://github.com/ide/react-native-button">ide/react-native-button</a></p><pre>npm install --save react-native-button</pre><p><strong>Creating the 100% perfect typings is a hard and unnecessary work</strong>. So we can do the following:</p><pre>touch src/declarations.d.ts</pre><p>If we use the <strong><em>any</em></strong> type, Typescript <strong>will not bother us about missing typings or wrong usage:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e5f91a540d79ca94ce13194abd75296/href">https://medium.com/media/4e5f91a540d79ca94ce13194abd75296/href</a></iframe><p>It’s easy and we get (rotated screen to show it better here at <em>Medium</em>):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I76uMQ8JqjPSUfqRSX5oVA.png" /></figure><p>It’s possible to improve the declared typings, take as example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5125e19d56ff73af37054a31633baeb0/href">https://medium.com/media/5125e19d56ff73af37054a31633baeb0/href</a></iframe><p>The usage still the same.</p><blockquote>There are not the full typings of the components, but you can see that we can make improvements over the time.</blockquote><h3>Conclusion</h3><p>The usage with Typescript is very simple. But <strong>it comes with risks</strong>:</p><ul><li>React (Facebook) has <a href="https://flowtype.org/"><strong><em>Flow</em></strong></a>. Even if it’s a annotation system, I think the invention of this has splitted the community. We could have a unique and common typings system for React and Angular. Maybe someday a combination of both of this technologies will be merged to the ECMAScript.</li><li>It’s hard to find modules with typings. <strong>Un-official support comes with compatibility problems because of outdated or incomplete typings.</strong></li><li>The typings conventions are still immature, so it’s common to have errors and it’s hard to find updated information and guides.</li><li>Perhaps it’s better to stick with <em>Flow</em> or keep using classic un-typed Javascript.</li></ul><p>Finally, a more complete example code is available at:</p><p><a href="https://github.com/mrpatiwi/ReactNativeTS">mrpatiwi/ReactNativeTS</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad57b7413ead" width="1" height="1" alt=""><hr><p><a href="https://medium.com/react-weekly/react-native-and-typescript-ad57b7413ead">React Native and Typescript</a> was originally published in <a href="https://medium.com/react-weekly">React Weekly</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular to React: tips on a smooth migration]]></title>
            <link>https://medium.com/react-weekly/angular-to-react-tips-on-a-smooth-migration-aafb57589995?source=rss----955bdba6e52f---4</link>
            <guid isPermaLink="false">https://medium.com/p/aafb57589995</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[SAP Conversational AI]]></dc:creator>
            <pubDate>Thu, 15 Sep 2016 06:46:17 GMT</pubDate>
            <atom:updated>2016-09-14T17:11:18.354Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*wS3gahM1NfLJpTof.jpg" /></figure><p><a href="https://angularjs.org/">AngularJS</a> is a pretty cool framework by Google — it provides many great features, like routing and two-way data binding. We used it to create the first version of our platform, but today, we see its limits and want to migrate our platform to ReactJS.</p><p>Angular helps creating single page applications and renders the content on the client-side, but is utterly bad in terms of SEO referencing. We want to have something that renders our content on the server-side at the first load, but provides the experience of the SPA applications after that: an isomorphic app. We also want to come back to Javascript, pure javascript, not an Angular abstraction, and further control our data stream.</p><h3>A little more about React and its environment</h3><p><a href="http://reactjs/">React</a> is an open source library built by Facebook.</p><p>React provides a high performance client and server side rendering with a one-way flow for data binding. It’s not a framework, that’s why we’re talking about React and all of its environnement friends.</p><h3>1.Flux:</h3><blockquote><em>“Flux is the application architecture that Facebook uses to build client-side web applications. It complements React’s composable view components by utilizing a unidirectional data flow. It’s more of a pattern than a formal framework” — </em><a href="https://facebook.github.io/flux/docs/overview.html"><em>Flux</em></a></blockquote><p>We chose <a href="http://redux.js.org/">Redux</a>, as a flux implementation, a predictable state container for JavaScript apps.</p><blockquote><em>“As the requirements for JavaScript single-page applications have become increasingly complicated, our code must manage more state than ever before. This state can include server responses and cached data, as well as locally created data that has not yet been persisted to the server. UI state is also increasing in complexity, as we need to manage the active route, the selected tab, whether to show a spinner or not, should pagination controls be displayed, and so on.</em></blockquote><blockquote><em>Managing this ever-changing state is hard. If a model can update another model, then a view can update a model, which updates another model, and this, in turn, might cause another view to update. At some point, you no longer understand what happens in your app as you have lost control over the when, why, and how of its state. When a system is opaque and non-deterministic, it’s hard to reproduce bugs or add new features.“</em></blockquote><h3>2.<a href="https://webpack.github.io/docs/motivation.html">Webpack</a>, a module bundler.</h3><p>Webpack takes modules with dependencies and generates static assets representing those modules.</p><h3>Refactor time</h3><p>How do we refactor our entire platform? Several methods are available. To prepare, we often go to React and JS meetups. One of them is exactly on our topic: how to migrate your website to React. The conclusion of the speaker is to migrate little by little, for months, and maintain all this crazy stack.</p><p>While that’s great advice, we decide against it. We use the summer to recode the entire platform in a rush and start form zero. We keep no files from the previous version, we create this entire new project. It takes four developers, and three weeks later here we are! Here’s how we made it work.</p><h3>A little preparation</h3><p>Before we started coding, we “printed” all of our current website to have a global view. That allowed us to easily analyse what we want to redo. This second version was going to be built on the UI foundations of the old one, with lot of little changes in UI-components to make a better user experience. So the key idea was to abstract website pieces in order to make re-usable multiple component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AtuLsvehhydPxRsW.jpg" /></figure><p>To make all of this more readable, we drew the component hierarchy. In <a href="https://facebook.github.io/react/docs/thinking-in-react.html">React documentation</a>, they call this “Break the UI into a component hierarchy”. The first thing you want to do is to draw boxes around every component (and subcomponent) in the mock and name them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CnhgGFndRCM_kKFh.jpg" /></figure><p>After the component hierarchy was set up, we took the time to work on our redux store.</p><p>The redux store holds the whole state of your application. We have to think about how our data will be structured and how our cache will work.</p><h3>The first line of code</h3><p>The first step was to migrate our stylesheets and in the same time to start a real web-styleguide. We took the opportunity to restructure our whole style, and to only keep some global component: typography, layout, buttons, input, etc. All other component will have their own stylesheet attached to them.</p><p>In order to have a great project structure, we based our architecture on one of our friends boilerplate: <a href="https://github.com/SIGSEV/minus">minus</a> a “React / Redux isomorphic starter, focused on minimalism and beauty”.</p><p>After that, the coding begins</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KuS3a2IY1e3sAQ5y.jpg" /></figure><p>We split the tasks between the four of us. It was important that each member could move forward without the work of the others. Some of us focused on dumb components and others on smart components.</p><p>One very important thing in our project was authentication. Due to an isomorphic app, backend and frontend share the same code, but some code had to be specific, like the cookie handle. So an isomorphic authentication was not really easy.</p><h3>And now?</h3><p>Thanks to the isomorphic app, we have an increased performance, mainly thanks to the initial pageload speed. The SEO problem is no more, single page app is crawlable. If you want other benefits due to isomorphic app, you can check this: <a href="http://nerds.airbnb.com/isomorphic-javascript-future-web-apps/">http://nerds.airbnb.com/isomorphic-javascript-future-web-apps/</a>. It’s a beautiful world.</p><p>With this second version, we’ve set up an advanced smooth rendering and navigation of our pages.</p><p>To do so, we’ve rendered content as quickly as possible, so we’re never stuck on a page waiting for data.</p><p>To achieve this, you need to flush async fragments. For instance, on this page, the structure loads first, then bloc number 1, and finishes with bloc number 2. Users can navigate smoothly and are never blocked on a page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jAFp8igiKBzsDT8O.jpg" /></figure><p>But one of the greatest benefit of our migration are the improved micro-interactions. All micro-interactions are easy to code with this new stack and really smooth for the user. You can fork a bot on the explore page. There is always an indicator of forking on the bot, wether you navigate on the explore or go back to your profile.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*7SFzZ-7-GlLZl5bME1bWFA.gif" /></figure><p>And that’s about it. So if you’re looking to migrate from Angular to React, go for it. It’ll be worth it.</p><p>We are working now on a big feature on the platform for October, and the front developers team is growing up, so if you want to know more, drop us a mail!</p><p>Jasmine ANTEUNIS — <a href="https://recast.ai/">Recast.AI</a></p><figure><a href="https://www.facebook.com/RecastAI/"><img alt="" src="https://cdn-images-1.medium.com/max/600/1*PRjNCtCqs3IYouSwxSCB1w.png" /></a></figure><figure><a href="https://twitter.com/RecastAI"><img alt="" src="https://cdn-images-1.medium.com/max/600/1*tJgdDqL_zGv46ufDO401WQ.png" /></a></figure><p><em>This post was originally published on </em><a href="https://blog.recast.ai/toward-augmented-dataset/"><em>our blog</em></a><em>. If you enjoyed it, you might also like: </em><a href="https://medium.com/@RecastAI/datasets-the-gold-of-machine-learning-17bea3a70ef1#.oewlpuws7"><em>Datasets, the gold of Machine Learning</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aafb57589995" width="1" height="1" alt=""><hr><p><a href="https://medium.com/react-weekly/angular-to-react-tips-on-a-smooth-migration-aafb57589995">Angular to React: tips on a smooth migration</a> was originally published in <a href="https://medium.com/react-weekly">React Weekly</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing GraphQL in your Redux App]]></title>
            <link>https://medium.com/react-weekly/implementing-graphql-in-your-redux-app-dad7acf39e1b?source=rss----955bdba6e52f---4</link>
            <guid isPermaLink="false">https://medium.com/p/dad7acf39e1b</guid>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Ryan C. Collins]]></dc:creator>
            <pubDate>Thu, 15 Sep 2016 02:42:46 GMT</pubDate>
            <atom:updated>2016-10-16T10:17:35.339Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*XotLYM6yuwS0Mqju7N9DSw.png" /></figure><p>This post aims to be a guide for implementing GraphQL into a Redux App. It goes over some of the realizations I made throughout the process of integrating it into my workflow. I expect that you have some amount of familiarity with the setup involved in React / Redux projects and will link to resources as I go.</p><p>While Redux at it’s core is a State management library, often times your action creators take care of loading data from your API. The method that I have used mostly is to implement thunks, along with having several actions / action creators to communicate between the store and UI during the data-loading process.</p><p>What this generally ends up looking like is the following:</p><pre>import {<br>  LOAD_EMPLOYEE_DATA_INITIATION,<br>  LOAD_EMPLOYEE_DATA_SUCCESS,<br>  LOAD_EMPLOYEE_DATA_FAILURE,<br>} from &#39;./constants&#39;;</pre><pre>export const employeeUrl = &#39;<a href="http://0.0.0.0:1338/api/employees&#39;">http://0.0.0.0:1338/api/employees&#39;</a>;</pre><pre>// loadEmployeeDataInitiation :: None -&gt; {Action}<br>export const loadEmployeeDataInitiation = () =&gt; ({<br>  type: LOAD_EMPLOYEE_DATA_INITIATION,<br>});</pre><pre>// loadEmployeeDataSuccess :: Array -&gt; {Action}<br>export const loadEmployeeDataSuccess = (data) =&gt; ({<br>  type: LOAD_EMPLOYEE_DATA_SUCCESS,<br>  data,<br>});</pre><pre>// loadEmployeeDataFailure :: Error -&gt; {Action}<br>export const loadEmployeeDataFailure = (error) =&gt; ({<br>  type: LOAD_EMPLOYEE_DATA_FAILURE,<br>  error,<br>});</pre><pre>export const loadEmployeeData = () =&gt;<br>  (dispatch) =&gt; {<br>    dispatch(<br>      loadEmployeeDataInitiation()<br>    );<br>    return fetch(employeeUrl)<br>      .then(res =&gt; res.json())<br>      .then(data =&gt; {<br>        dispatch(<br>          loadEmployeeDataSuccess(data)<br>        );<br>      })<br>      .catch(error =&gt; {<br>        dispatch(<br>          loadEmployeeDataFailure(error)<br>        );<br>      });<br>  };</pre><p>The pattern here is to essentially represent the control flow of your data via the dispatching (via a <a href="https://github.com/gaearon/redux-thunk">thunk</a>) of actions at various stages of your asynchronous control flow.</p><p>I actually really like this pattern. I think that it works very well for the majority of my data-fetching needs. So why, you ask, would I even want to use GraphQL?</p><h3>About GraphQL</h3><p>GraphQL is a declarative query language, created by <a href="http://leebyron.com/">Lee Byron</a> of Facebook. The initial reason why I wanted to learn GraphQL is because basically everything that comes out of Facebook is golden. Lee has supplanted himself and Facebook as one of the major thought leaders in the space and I trust his/their judgement. He brought us <a href="https://facebook.github.io/immutable-js/">ImmutableJS</a>, an implementation of persistent immutable data structures in JavaScript, the <a href="https://facebook.github.io/react/docs/component-specs.html">life-cycle methods</a> in React, several contributions to the <a href="http://www.ecma-international.org/memento/TC39.htm">TC39 committee</a>. Anyways, Lee and his colleagues know their stuff.</p><p>The major accomplishment of GraphQL, in my opinion, is that it inverts control of the server layer to the client. Commonly, REST architecture leaves the control of the data layer to the server. It is common nowadays to build APIs in a micro-service oriented manner, whereby the API is built in isolation of the client application and the two are connected via RESTFul endpoints.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9udUHk9csNBCUdrepUqZzQ.png" /><figcaption>Typical RESTful Client Server Model</figcaption></figure><p>The problem with RESTful endpoints, especially at a large scale, is that the control of the data returned from custom endpoints generally lies in the hands of the server developer. We can fake some amount of control using query parameters, but ultimately the client-side developer is at the whim of the server.</p><p>As our front ends grow more and more complex, this model starts to show its weaknesses. Over-fetching of data, multiple round trips per request, misunderstanding of the data model. It also becomes hard to maintain RESTful APIs over time because changes to the models require significant amounts of planning in order to ensure that they aren’t breaking the system.</p><p>GraphQL aims to invert the control of data flow, giving control to the front end developer. It gives them the power to define their data needs, while also optimizing the entire experience, solving many of the problems of the custom endpoint approach. On top of that, the language is highly declarative and the process of expressing your data needs fits right into the client-side development flow that many of us have become accustomed to with React.</p><h3>Back to the point</h3><p>Now that we have a bit of the history behind us and a greater understanding of where GraphQL fits in, we can explore a bit about why we would want to integrate GraphQL into our Redux applications and how we would go about doing it.</p><p>GraphQL, although extremely powerful, is just one part of the picture. In order to integrate it into a React/Redux application, we could use some help. This is where Apollo and Relay fit into the picture. Both intend to bridge the gap and provide the missing implementation boilerplate that makes the integration a seamless experience. I am choosing to focus on Apollo, but I’d love to use Relay and will leave that to a future article.</p><h3>Apollo</h3><p>The integration of Apollo into a Redux application is very straight forward because Redux is baked into Apollo Client, the library we’ll be using here. Before we get into integrating Apollo Client into our front end workflow, let’s go over the basics of setting us up on the server side.</p><h3>Server Setup</h3><p>With Node, Express and a few GraphQL related libraries, the server setup is fairly simple. In my example, I chose to completely forego any database setup and I generated some random JSON and CSV data that I used instead of a database.</p><p>You’ll have to keep in mind that this is not an example of a production setup, but is rather an example of how you can start messing around with GraphQL today.</p><pre>// server/schema/schema.js<br>import {<br>  GraphQLSchema,<br>  GraphQLObjectType,<br>  GraphQLInt,<br>  GraphQLString,<br>  GraphQLList,<br>} from &#39;graphql&#39;;</pre><pre>import issuesJSON from &#39;../data/issues.json&#39;;<br>import employeesJSON from &#39;../data/employees.json&#39;;<br>import _ from &#39;lodash&#39;;<br>import fs from &#39;fs&#39;;<br>import path from &#39;path&#39;;<br>const store = {};</pre><pre>// Some helper methods to load CSV into JSON, which were removed for brevity&#39;s sake.</pre><pre>const customerJson = loadCsv();</pre><pre>const CustomerType = new GraphQLObjectType({<br>  name: &#39;Customer&#39;,<br>  fields: () =&gt; ({<br>    week_num: { type: GraphQLInt },<br>    num_customers: { type: GraphQLInt },<br>  }),<br>});</pre><pre>const PersonType = new GraphQLObjectType({<br>  name: &#39;Person&#39;,<br>  fields: () =&gt; ({<br>    name: { type: GraphQLString },<br>    avatar: { type: GraphQLString },<br>    company: { type: GraphQLString },<br>  }),<br>});</pre><pre>const EmployeeType = new GraphQLObjectType({<br>  name: &#39;Employee&#39;,<br>  fields: () =&gt; ({<br>    id: { type: GraphQLString },<br>    numemployees: { type: GraphQLInt },<br>    location: { type: GraphQLString },<br>  }),<br>});</pre><pre>const IssueType = new GraphQLObjectType({<br>  name: &#39;Issue&#39;,<br>  fields: () =&gt; ({<br>    id: { type: GraphQLString },<br>    submission: { type: GraphQLString },<br>    closed: { type: GraphQLString },<br>    status: { type: GraphQLString },<br>    customer: { type: PersonType },<br>    employee: { type: PersonType },<br>    description: { type: GraphQLString },<br>  }),<br>});</pre><pre>const StoreType = new GraphQLObjectType({<br>  name: &#39;Store&#39;,<br>  fields: () =&gt; ({<br>    employees: {<br>      type: new GraphQLList(EmployeeType),<br>      resolve: () =&gt; employeesJSON,<br>    },<br>    issues: {<br>      type: new GraphQLList(IssueType),<br>      resolve: () =&gt; issuesJSON,<br>    },<br>    customers: {<br>      type: new GraphQLList(CustomerType),<br>      resolve: () =&gt; customerJson,<br>    },<br>  }),<br>});</pre><pre>const QueryType = new GraphQLObjectType({<br>  name: &#39;Query&#39;,<br>  fields: () =&gt; ({<br>    store: {<br>      type: StoreType,<br>      resolve: () =&gt; store,<br>    },<br>  }),<br>});</pre><pre>export default new GraphQLSchema({<br>  query: QueryType,<br>});</pre><p>Above is a very simple schema definition that we use to describe our data to GraphQL. If you were hooking this into a database, you would be making calls to it in the resolve functions you see above instead of returning the data loaded from the mock JSON files. The reason that we define a schema will be discussed more in detail later, but the idea is that we can generate a structure and assign types to our data to make <a href="https://en.wikipedia.org/wiki/Static_program_analysis">static analysis</a> possible.</p><p>We wrap our data in a root level key that we are calling Store here in so that when we query our data, it will be wrapped in a root level object. This is something that you might be used to if you’ve used the Rails ActiveModel Serializers Gem with the <a href="https://github.com/rails-api/active_model_serializers/blob/master/docs/general/adapters.md">JSON API adapter type</a> before. As shown below, it acts as a root level key in our queries. This is really just a preference thing and you can take it or leave it.</p><pre>query Customers {<br>    store {<br>      customers {<br>        week_num<br>        num_customers<br>      }<br>    }<br>  }</pre><p>With our schema defined, we can now tell our Express server to serve the data through an endpoint using the GraphQL Express library.</p><pre>// server/app.js<br>import &#39;regenerator-runtime/runtime&#39;;<br>import express from &#39;express&#39;;<br>import path from &#39;path&#39;;<br>import fs from &#39;fs&#39;;<br>import { graphql } from &#39;graphql&#39;;<br>import { introspectionQuery } from &#39;graphql/utilities&#39;;<br>import schema from &#39;./schema/schema&#39;;<br>import morgan from &#39;morgan&#39;;<br>import cors from &#39;cors&#39;;</pre><pre>// constants needed<br>const isDeveloping = process.env.NODE_ENV !== &#39;production&#39;;<br>const port = isDeveloping ? 1338 : process.env.PORT;<br>const app = express();<br>const graphqlHTTP = require(&#39;express-graphql&#39;);<br>const query = &#39;query { employees { id, numemployees, location }}&#39;;</pre><pre>if (isDeveloping) {<br>  app.all(&#39;*&#39;, (req, res, next) =&gt; {<br>    res.header(&#39;Access-Control-Allow-Origin&#39;, &#39;*&#39;);<br>    res.header(&#39;Access-Control-Allow-Methods&#39;, &#39;GET, POST&#39;);<br>    res.header(&#39;Access-Control-Allow-Headers&#39;, &#39;Content-Type&#39;);<br>    next();<br>  });<br>  app.use(morgan(&#39;combined&#39;));<br>}</pre><pre>app.use(express.static(__dirname + &#39;/public&#39;));</pre><pre>graphql(schema, query).then((result) =&gt; {<br>  console.log(JSON.stringify(result))<br>});</pre><pre>(async () =&gt; {<br>  try {<br>    app.use(<br>      &#39;/api&#39;,<br>      cors(),<br>      graphqlHTTP({ schema, pretty: true, graphiql: true })<br>    );</pre><pre>    app.get(&#39;*&#39;, (req, res) =&gt; {<br>      res.sendFile(path.join(__dirname, &#39;public/index.html&#39;));<br>    });</pre><pre>    app.listen(port, &#39;0.0.0.0&#39;, (err) =&gt; {<br>      if (err) { return console.warn(err); };<br>      return console.info(<br>        `==&gt; 😎 Listening on port ${port}.<br>          Open <a href="http://0.0.0.0:${port}/">http://0.0.0.0:${port}/</a> in your browser.`<br>      );<br>    });</pre><pre>    let json = await graphql(schema, introspectionQuery);<br>    fs.writeFile(<br>      &#39;./server/schema/schema.json&#39;,<br>      JSON.stringify(json, null, 2),<br>      err =&gt; {<br>        if (err) throw err;<br>        console.log(&quot;JSON Schema Created&quot;)<br>      });<br>  } catch (err) {<br>    console.log(err);<br>  }<br>})();</pre><p>Now, it may look like there is a lot going on here, but really it is fairly simple. Most of this is really just boilerplate Express stuff, for example we are using CORS and Morgan when the app is in development in order to make our lives easier. We are also setting our access control headers.</p><p>The async <a href="https://en.wikipedia.org/wiki/Immediately-invoked_function_expression">IIFE</a> that you see here is just a neat use of the Async Await feature that will be released, I believe, in the next formal JavaScript specification. It allows us to write the GraphQL schema into a schema.json file asynchronously using the new syntax. The generation of this file is part of the process.</p><p>Note, to get this working, you will need to have a file that first requires babel-core/register and then loads up the express server.</p><p>To do this, I’ve created a root level server.js file with the following:</p><pre>require(&#39;babel-core/register&#39;);<br>var app = require(&#39;./server/app&#39;);</pre><h3>Clientside setup</h3><p>Now we can move onto the client-side setup. I began this project as a fork of my own <a href="https://github.com/RyanCCollins/scalable-react-boilerplate">React Boilerplate</a>, where I have all of the boilerplate setup for React / Redux. My boilerplate aims to modularize React applications, and thus the setup was a bit different from the guide located on the <a href="http://dev.apollodata.com/react/redux.html">ApolloClient site</a>.</p><p>The main difference between the code on the site is that I separate out my Routes, Store and Reducer into separate modules, which you can see if you take a look at my <a href="https://github.com/RyanCCollins/scalable-react-boilerplate">boilerplate project</a>. For this reason, I suggest creating a new file called apolloClient, that you will use as a singleton in multiple files.</p><pre>// /app/src/apolloClient.js<br>import ApolloClient, {<br>  createNetworkInterface,<br>  addTypeName,<br>} from &#39;apollo-client&#39;;</pre><pre>const client = new ApolloClient({<br>  networkInterface: createNetworkInterface(&#39;<a href="http://0.0.0.0:1338/api&#39;">http://0.0.0.0:1338/api&#39;</a>),<br>  queryTransformer: addTypeName,<br>});</pre><pre>export default client;</pre><p>Make sure that you set your network interface URL to the same endpoint that we created early in the Express setup.</p><p>Now, we need to use this client in multiple places in our App:</p><pre>// /app/src/reducers.js<br>import client from &#39;./apolloClient&#39;;</pre><pre>const rootReducer = combineReducers({<br>  // ... Other reducers go here<br>  routing: routerReducer,<br>  form: formReducer,<br>  apollo: client.reducer(),<br>});</pre><pre>/ /app/src/routes<br>import { ApolloProvider } from &#39;react-apollo&#39;;<br>import client from &#39;./apolloClient&#39;;<br>/* eslint-enable */</pre><pre>const routes = (<br>  &lt;ApolloProvider store={store} client={client}&gt;<br>    &lt;Router history={history}&gt;<br>      &lt;Route path=&quot;/&quot; component={App}&gt;<br>        &lt;IndexRoute component={Pages.LandingPage} name=&quot;Home&quot; /&gt;<br>        &lt;Route path=&quot;*&quot; component={Pages.NotFoundPage} /&gt;<br>      &lt;/Route&gt;<br>    &lt;/Router&gt;<br>  &lt;/ApolloProvider&gt;<br>);<br></pre><pre>// /app/src/store.js<br>import client from &#39;./apolloClient&#39;;<br>const loggerMiddleware = createLogger();<br>const middlewares = [thunk, loggerMiddleware, client.middleware()];</pre><pre><br>const enhancers = [];<br>const devToolsExtension = window.devToolsExtension;<br>if (typeof devToolsExtension === &#39;function&#39;) {<br>  enhancers.push(devToolsExtension());<br>}</pre><pre>const composedEnhancers = compose(<br>  applyMiddleware(...middlewares),<br>  ...enhancers<br>);</pre><pre>const store = createStore(<br>  rootReducer,<br>  initialState,<br>  composedEnhancers,<br>);</pre><p>The three important pieces here are that we need to get setup is</p><ol><li>We need to make a reducer that will act as our representative for the apollo client within our store.</li><li>We also need to hook up our ApolloClient singleton to our application via the ApolloProvider, a HOC that sits around our routes in this case.</li><li>Finally, we need to add the ApolloClient middleware to our store.</li></ol><p>This may seem like a lot of boilerplate, and well it is. Similarly to Redux, once we have this boilerplate setup, our application development process is extremely streamlined and declarative.</p><p>By wiring in the ApolloClient, we are now free to carry on using Redux as we were before, while using GraphQL to replace our Thunks from earlier.</p><p>Within our containers, we can create declarative query strings that Apollo will handle the details of executing clientside. At this point, a container might look something like this</p><pre>import React, { Component, PropTypes } from &#39;react&#39;;<br>import { connect } from &#39;react-redux&#39;;<br>import { bindActionCreators } from &#39;redux&#39;;<br>import * as KeyMetricsViewActionCreators from &#39;./actions&#39;;<br>import gql from &#39;graphql-tag&#39;;<br>import { graphql } from &#39;react-apollo&#39;;<br>import cssModules from &#39;react-css-modules&#39;;<br>import styles from &#39;./index.module.scss&#39;;<br>import Heading from &#39;grommet/components/Heading&#39;;<br>import { LineChart } from &#39;components&#39;;</pre><pre>class KeyMetricsView extends Component {<br>  render() {<br>    const {<br>      loading,<br>      store,<br>      areaChartLabels,<br>    } = this.props;<br>    return (<br>      &lt;div className={styles.keyMetricsView}&gt;<br>        &lt;Heading align=&quot;center&quot;&gt;<br>          Key Metrics<br>        &lt;/Heading&gt;<br>        {loading ?<br>          &lt;Heading tag=&quot;h2&quot; align=&quot;center&quot;&gt;Loading&lt;/Heading&gt;<br>        :<br>          &lt;LineChart<br>            data={store.customers}<br>            labels={areaChartLabels}<br>          /&gt;<br>        }<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><pre>KeyMetricsView.propTypes = {<br>  store: PropTypes.array.isRequired,<br>  areaChartLabels: PropTypes.array.isRequired,<br>  loading: PropTypes.bool.isRequired,<br>  error: PropTypes.object,<br>};</pre><pre>// mapStateToProps :: {State} -&gt; {Props}<br>const mapStateToProps = (state) =&gt; ({<br>  areaChartLabels: state.keyMetrics.areaChartLabels,<br>});</pre><pre>// mapDispatchToProps :: Thunk -&gt; {Action}<br>const mapDispatchToProps = (dispatch) =&gt; ({<br>  actions: bindActionCreators(<br>    KeyMetricsViewActionCreators,<br>    dispatch<br>  ),<br>});</pre><pre>const allCustomers = gql`<br>  query allCustomer {<br>    store {<br>      customers {<br>        week_num<br>        num_customers<br>      }<br>    }<br>  }<br>`;</pre><pre>const ContainerWithData = graphql(allCustomers, {<br>  props: ({ data: { loading, store } }) =&gt; ({<br>    store,<br>    loading,<br>  }),<br>})(KeyMetricsView);</pre><pre>const Container = cssModules(ContainerWithData, styles);</pre><pre>export default connect(<br>  mapStateToProps,<br>  mapDispatchToProps,<br>)(Container);</pre><p>Notice how we are still able to continue using connected Redux components. To me, this is the best of both worlds. Once you have this wired up, you will see that behind the scenes, ApolloClient is taking care of the asynchronous action creators for us and we no longer need to follow the model mentioned earlier.</p><p>This setup allowed me to get my hands dirty with GraphQL without giving up Redux. When I have a better understanding of how Relay fits into that same picture, perhaps I will give it the ‘ol College try, but for now I am very happy with this setup.</p><p>In this example, what I am really trying to show you is that the GraphQL setup with ApolloClient is very similar to what we are already doing with Redux. It allows us to wrap our container with a function that maps the data returned from our Query to properties that we can using in our React container and pass down to our Children.</p><p>ApolloClient behind the scenes is doing almost exactly what we were manually doing earlier with our Thunks. It is sending Redux actions at each stage of the control flow. The benefit, if you choose to see it that way, is that it takes care of abstracting away those details.</p><h3>Inversion of Control</h3><p>Back to the point, GraphQL flips the entire server relationship model on its head. It gives us, the people who are actually building the client-facing application UI complete control over our data needs. It does so while remaining flexible and performant, cutting down on refetches and preventing over-fetching. It lets us represent our data needs declaratively and helps to bridge the gap between the client and server.</p><p>It also encourages exploration of data. Using the GraphiQL IDE, which can be enabled with the Express GraphQL library, the client-side developer has a tool that they can use to get their hands on the actual data by writing GraphQL queries in the browser. Take a look at <a href="https://www.graphqlhub.com/">GraphQLHub</a> to see what I mean. I’ve been spending some time getting my Data Science friends pumped on the idea of using GraphQL as part of a data science pipeline. I can see it being useful in a number of other domains where having control over representing your data needs as a Graph would come in handy.</p><p>What you are seeing in action with the GraphiQL IDE is the static analysis that GraphQL is able to do behind the scenes. The GraphQL specification makes key the concept of allocating types to your data schema, providing a mechanism to perform static analysis. As you are typing out your query within the GraphiQL IDE, you will see instant feedback, including intelligent autocompletion and syntax error highlighting. All of this is made possible by mechanisms built right into the GraphQL specification.</p><p>Beyond the purview of this article, these tools provide even more powerful data fetching facilities, such as optimistic UI, pagination, mutations, and many others. Relay has client-side caching built right into it, and manages many of the complexities of loading massively complex feeds of data.</p><h3>More Resources</h3><p>Hopefully this article has gotten you pumped about integrating GraphQL into your app. I hope to write more articles like this in the future as I get more hands on time with a production setup. In the meantime, here are some of the resources that I used to learn about GraphQL and the accompanying tools and libraries.</p><ul><li><a href="http://www.apollostack.com/">Apollo</a> Stack website</li><li><a href="https://learngraphql.com/">Learn GraphQL</a></li><li><a href="http://graphql.org/learn/">GraphQL Documentation</a></li><li><a href="https://facebook.github.io/relay/docs/getting-started.html">Relay Documentation</a></li><li><a href="https://facebook.github.io/graphql/">GraphQL Specification</a> — This document is especially useful if you are serious about integrating GraphQL.</li><li><a href="https://medium.com/apollo-stack/the-concepts-of-graphql-bc68bd819be3#.94scr3agl">GraphQL Concepts Visualized</a> — An amazing article that explores how our data can be expressed by <a href="https://en.wikipedia.org/wiki/Graph_theory">Graphs</a>.</li></ul><p>The application that I built can be <a href="https://github.com/RyanCCollins/corporate-dashboard">found here for reference</a>, although I must warn that I am still working on the app, so it could break over the next week.</p><p>Enjoyed this article? Please make sure to tap the like button below!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*xEyJy8UmyaF1Wmjn4xjZTQ.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dad7acf39e1b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/react-weekly/implementing-graphql-in-your-redux-app-dad7acf39e1b">Implementing GraphQL in your Redux App</a> was originally published in <a href="https://medium.com/react-weekly">React Weekly</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Relay/GraphQL On Rails]]></title>
            <link>https://medium.com/react-weekly/relay-facebook-on-rails-8b4af2057152?source=rss----955bdba6e52f---4</link>
            <guid isPermaLink="false">https://medium.com/p/8b4af2057152</guid>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[relayjs]]></category>
            <category><![CDATA[graphql]]></category>
            <dc:creator><![CDATA[Soon Hin Khor, Ph.D.]]></dc:creator>
            <pubDate>Mon, 12 Sep 2016 20:00:28 GMT</pubDate>
            <atom:updated>2019-05-18T01:51:05.685Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*ml4H68gOogx8uCYqhfUNSA.png" /></figure><p>Summary: <em>If you are excited about just declaring data required by your UI components while leaving the difficult parts of data fetching, updating, and data handling performance issues to a framework, you will be excited by Facebook’s recent release of Relay/RelayJS (Sep 2015), which works with React UI (Oct 2014). This article shows you how to to integrate Relay/React into Rails.</em></p><p><strong>NOTE:</strong></p><ul><li>You can clone this starter-kit from <a href="https://github.com/nethsix/relay-on-rails">Github</a>, and start using Relay immediately without reading further</li><li>Conversely, with instructions here you can re-create the starter-kit on Github</li></ul><p>Facebook introduced <a href="https://facebook.github.io/react/blog/2014/10/28/react-v0.12.html">React</a> (Oct 2014) to make creating rich web UI easy to reason, and debug with its uni-directional data flow; all data required by the entire web UI on a page is piped through a top-level UI component, which percolates only the necessary data to each sub-components under it.</p><p>However, the React component (usually the top-level component), or the optional <a href="https://facebook.github.io/flux/">Flux</a> framework (if you implemented it), is still responsible for fetching the required data using Ajax, etc., and you have to write that.</p><p>Enter <a href="https://facebook.github.io/relay/">Relay</a>! When you create a React component, you just need to declare the data that it needs, and Relay will handle the gory details of fetching the data efficiently, which includes batching queries, collapsing access patterns, caching, etc.</p><h3>Overview</h3><p><strong>Assumptions</strong>:</p><ul><li>You have Rails installed (tested on Rails 4.2 only)</li><li>You have &gt;= ruby-2.1</li></ul><p><strong>Goals</strong>:</p><ul><li>Make it easy to understand (see <strong>Relay in Pictures </strong>section) Relay</li><li>Setup Relay/React on Rails so that we can create a very simple Rails/Relay/React application, which outputs to the browser:</li></ul><pre>The Board!<br>Boarding… Simpleton</pre><p><strong>NOTE</strong>: The 2nd line ‘<em>Boarding… Simpleton</em>’ is a React component, which relies on Relay to pull its data (<em>Simpleton</em>) from the server over the Internet.</p><ul><li>Use this setup as a foundation to further experiment with Relay</li></ul><p><strong>Why this is difficult</strong>:</p><p>As of this writing (15 Sep 2015), I could not find any information on getting Facebook’s Github <a href="https://github.com/facebook/relay">Relay</a> or npm-based ‘<a href="https://www.npmjs.com/package/react-relay">react-relay</a>’ to work with Rails.</p><p>The existing Facebook tutorial:</p><ul><li>Does not show clear distinction between client-side, and server-side library requirements because in its case, both use Javascript libraries. Specifically, it does not address the question — “<em>which libraries are required to make a non-Javascript-based server Relay-capable, and which libraries should be delivered to the browser to make the client-side Relay-capable?</em>”</li></ul><pre>// nodejs npm package.json<br>// Source from Facebook&#39;s Github <a href="https://github.com/facebook/relay/blob/master/examples/relay-treasurehunt/package.json">Relay repo</a><br>// Which libraries are client-side &amp; which are server-side?</pre><pre>“dependencies”: {<br> “babel”: “5.8.23”,<br> “babel-loader”: “5.3.2”,<br> “babel-relay-plugin”: “file:../../scripts/babel-relay-plugin/”,<br> “classnames”: “^2.1.3”,<br> “express”: “^4.13.1”,<br> “express-graphql”: “^0.3.0”,<br> “graphql”: “^0.4.2”,<br> “graphql-relay”: “^0.3.1”,<br> “react”: “^0.14.0-rc”,<br> “react-dom”: “^0.14.0-rc”,<br> “react-relay”: “file:../../”,<br> “webpack”: “^1.10.5”,<br> “webpack-dev-server”: “^1.10.1”<br> }</pre><ul><li>Has no information on how to transpile Relay/GraphQL client-side Javascript code, which may reside on a non-Javascript-based server, but needs to be delivered to browser for execution</li></ul><pre>// Relay/GraphQL code to get &#39;name&#39; data from our<br>// &#39;simple&#39; data model<br>// The browser does not understand GraphQL, so this needs<br>// to be transpiled to Javascript before delivery to the browser</pre><pre>simple: () =&gt; Relay.QL`<br>      fragment on Simple {<br>        name<br>      }<br>    `</pre><ul><li>Is not Rails-based so you need to hunt down nuggets of information from all over the web</li></ul><h3>Relay In Pictures</h3><p>Relay consists of<a href="https://facebook.github.io/relay/docs/getting-started.html"> 3 parts</a>:</p><ol><li>The schema for our data specified in GraphQL</li><li>A GraphQL server, which can load up the schema, and respond to client queries in GraphQL</li><li>A ‘transport’ layer through which a client communicates with the GraphQL server via GraphQL language</li></ol><p>For our purpose, architecturally, this translates to:</p><ul><li>A Rails server acting as a GraphQL server serving our data based on our schema (requirement 1. &amp; 2.)</li><li>The Rails server delivering the necessary client-side Javascripts required for the browser to communicate with the GraphQL server through the Relay ‘transport’ layer, using the pre-agreed data schema (requires 1. &amp; 3.)</li></ul><p>To facilitate understanding, we illustrate the Relay nodejs setup used by the Facebook tutorial, and then compare what that setup should look like for Rails.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*QLF24OhWHyOFGnq4ri_V3Q.png" /><figcaption>nodejs Relay Setup</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*VRno9FFSfQX4x7plsWeaZg.png" /><figcaption>Rails Relay Setup</figcaption></figure><p>Things of note:</p><ul><li>Our GraphQL data schema (bottom-left box) is in either Javascript (nodejs server) or Ruby (Rails sever) but is converted using a npm script (nodejs) / Rake task (Rails) to JSON (follow the arrow upwards from the bottom-left box); nodesjs/Rails server-side code can use the GraphQL schema in Javascript/Ruby format, but <em>babel-relay-plugin</em> (more on this in next) needs it in JSON format</li><li>Transpilation of Relay.QL code (top-left box) to Javascript is done by <em>babel </em>(nodejs)<em> / babelify </em>(Rails) with the help of the <em>babel-relay-plugin</em> based on GraphQL data schema (JSON format)</li><li>We can clearly see what libraries are needed to make nodejs/Rails speak GraphQL, enabling it to host a <em>/graphql</em> endpoint (bottom-right box); the arrows from libraries/Gems pointing to the ‘Pure JS server-side <em>/graphql</em> endpoint’ (bottom-right box)</li><li>All Javascript code that needs to be delivered to the client-side (top-right box) is bundled using <em>webpack </em>(nodejs)<em> / browerify-rails</em> (Rails), which is also where transpilation is configured</li></ul><p>Let us look at how we can setup each component in detail next.</p><h3>Rails GraphQL Server</h3><h4>GraphQL-speaking Rails</h4><p>Add the following gems and run ‘<em>bundle install</em>’:</p><pre># Gemfile</pre><pre>gem ‘graphql’ <br>gem ‘graphql-relay’</pre><p><a href="https://github.com/rmosolgo/graphql-ruby/"><em>graphql-ruby</em></a> bestows Ruby with the ability to understand GraphQL, while <a href="https://github.com/rmosolgo/graphql-relay-ruby/"><em>graphql-relay-ruby</em></a> provides helpers to handle Relay specific-concepts such as:</p><ul><li>Associating a piece of data with a global id to facilitate re-fetching</li><li>Tying a piece of data with associated data, e.g., a piece of data representing a <em>Person</em>, can have many associated pieces of data about each of his <em>Friend</em></li><li>Updating a piece of data with input from client (Relay uses the fancy term ‘mutation’)</li></ul><h4>GraphQL<strong> Data Schema</strong></h4><p>Facebook’s official <a href="https://facebook.github.io/relay/docs/tutorial.html#authoring-a-schema">tutorial</a> shows how we can use GraphQL for data schema definition. Unlike the tutorial, instead of defining the data schema in Javascript (<em>data/schema.js</em>), we define it using <em>graphql-ruby</em> classes in a set of files under <em>app/graph</em>.</p><p>We will present a very simple GraphQL schema here as it is a huge topic, and Facebook’s tutorial has covered it quite a bit.</p><p>A GraphQL schema consists of a <em>Query</em>, and <em>Mutation</em> type, for handling queries and updates respectively. Each of these is compose-able out of other GraphQL types, e.g., our <em>Simple</em> query is composed from <em>SimpleType</em> (see below).</p><p>The first thing that you need to implement for the schema is the standard <em>NodeIdentification</em> interface; each piece of data that a client fetches through Relay/GraphQL comes from an instance object, e.g., an ActiveRecord, in Rails. Each of them is also assigned a global ID, that when passed back to Relay/GraphQL, enables Relay/GraphQL to re-fetch that same instance object (whose data may have changed). For more details read <a href="https://medium.com/@khor/relay-graphql-de-mystifying-node-id-38757121b9c">this</a>, but in the same vein as Facebook’s Relay tutorial, this was introduced at the start.</p><pre># app/graph/types/node_identification.rb</pre><pre>GraphQL::Relay::GlobalNodeIdentification.instance_variable_set(:<a href="http://twitter.com/instance">@instance</a>, nil)</pre><pre>NodeIdentification = <br>  GraphQL::Relay::GlobalNodeIdentification.define do<br>    object_from_id -&gt; (id) do<br>      type_name, id = NodeIdentification.from_global_id(id)<br>      type_name.constantize.find(id)<br>    end</pre><pre>type_from_object -&gt; (object) do<br>      RelayOnRailsSchema.types[object.class.name]<br>    end<br>end</pre><p>Next, let us look at the GraphQL schema <em>Query</em> (but leave out <em>Mutation</em> as an exercise).</p><pre># app/graph/types/query_type.rb</pre><pre>QueryType = GraphQL::ObjectType.define do<br>  name “Query”<br>  description “The query root for this schema”</pre><pre>  field <em>:simple</em> do<br>    type SimpleType<br>    description “Simple Stuff”<br>    resolve -&gt; (obj, args, ctx) do<br>      Hashie::Mash.new( { id: rand(1000), name: ‘Simpleton’ } )<br>    end<br>  end</pre><pre>  field <em>:node</em>, field: NodeIdentification.field<br>end</pre><p>This schema enables us to query data by either of the fields:</p><ul><li><em>:simple</em> with some arguments (<em>args</em>)</li><li><em>:node</em> id</li></ul><p>Under the <em>:simple</em> field:</p><ul><li><em>resolve</em> tells us how to get the data. In this case, we merely return a constant hash. However, if arguments were provided in the GraphQL query, e.g., a user email, we can access it in <em>args</em> and fetch data based on it by replacing <em>resolve</em> with:</li></ul><pre># app/graph/types/query_type.rb</pre><pre>... <br> resolve -&gt; (obj, args, ctx) do<br>    # Using ActiveRecord for Person Model<br>    Person.find_by_email(args[:email])<br>  end<br>...</pre><ul><li>S<em>impleType</em> defines the structure of the data we fetch (<em>app/graph/types/simple_type.rb</em>)</li></ul><pre># app/graph/types/simple_type.rb</pre><pre>SimpleType = GraphQL::ObjectType.define do<br>  name “Simple”<br>  description “Simple”<br>  interfaces [NodeIdentification.interface]<br>  global_id_field :id<br>  field :name, !types.String, “Simple name”<br>end</pre><p>We bind the Query type into our data schema in <em>app/graph/relay_on_rails.rb</em>. This is also where you bind a Mutation type if you have one.</p><pre># app/graph/relay_on_rails.rb</pre><pre>RelayOnRailsSchema = GraphQL::Schema.new(query: QueryType)</pre><p>To ensure that Rails can find our schema in <em>app/graph/types</em>, add to <em>config/application.rb</em>:</p><pre># config/application.rb</pre><pre># Load all graphql types<br>config.autoload_paths &lt;&lt; Rails.root.join(‘app’, ‘graph’, ‘types’)</pre><p>At this stage you can test that Rails can speak GraphQL through the <em>RelayOnRailsSchema</em> object, by firing up your Rails console:</p><pre># rails console</pre><pre>&gt; query_string = “query SimpleQuery { simple { name } }” <br>=&gt; “query SimpleQuery { simple { name } }”</pre><pre>&gt; RelayOnRailsSchema.execute(query_string)<br>=&gt; {“data”=&gt;{“simple”=&gt;{“name”=&gt;”Simpleton”}}}</pre><h4>GraphQL Endpoint</h4><p>With Rails speaking GraphQL, and understanding our data schema, all we need now is to expose the GraphQL endpoint <em>/graphql</em> that the client-side Relay ‘transport’ communicates to by default.</p><p>Define the <em>/graphql</em> endpoint in <em>config/routes.rb</em>:</p><pre># config/routes.rb</pre><pre>scope ‘/graphql’ do<br>  post”/”, to: “graphql#create”<br>end</pre><p>Handle the <em>/graphql</em> endpoint with the <em>GraphqlController#create</em> method in <em>app/controllers/graphql_controller.rb</em>.</p><pre>class GraphqlController &lt; ApplicationController<br>  # Ignore CSRF, rely on some auth token<br>  protect_from_forgery :except =&gt; [:create]</pre><pre>  def create<br>    query_string = params[:query]<br>    query_variables = params[:variables] || {}<br>    query = GraphQL::Query.new(RelayOnRailsSchema, query_string, variables: query_variables)<br>    render json: query.result<br>  end<br>end</pre><p>Start the rails server using rails s within the root directory.</p><p>Now test the endpoint from the command line:</p><pre># Command line</pre><pre>$ curl -d “query=query SimpleQuery { simple { name } }” <a href="http://localhost:3000/graphql">http://localhost:3000/graphql</a></pre><pre>&gt; {&quot;data&quot;:{&quot;simple&quot;:{&quot;name&quot;:&quot;Simpleton&quot;}}}</pre><p>The Rails GraphQL server is now ready.</p><h3>Serving Client-side Relay Javascripts</h3><h4>Relay/React Javascript Libraries</h4><p>From the <em>Rails Relay Setup</em> illustration, we know that we need to deliver Relay/React Javascript libraries (<em>react</em>, <em>react-relay</em>, etc.) to the client-side. We prepare them on the server-side first with <a href="https://www.npmjs.com/"><em>npm</em></a> which relies on a <em>package.json</em> file that specifies all the Javsacript libraries:</p><pre>// package.json</pre><pre>{<br>  “name”: “relay_on_rails”,<br>  “license”: “MIT”,<br>  “engines”: {<br>    “node”: “&gt;= 0.10”<br>  },<br>  “dependencies”: {<br>    “babel-relay-plugin”: “^0.2.5”,<br>    “babelify”: “^6.3.0”,<br>    “browserify”: “~&gt; 10.2.4”,<br>    “browserify-incremental”: “^3.0.1”,<br>    “graphql”: “^0.4.4”,<br>    “react”: “^0.14.0-rc1”,<br>    “react-dom”: “^0.14.0-rc1”,<br>    “react-relay”: “^0.3.2”<br>  }<br>}<br></pre><p>Do:</p><pre>npm install</pre><p>Which downloads all the libraries into <em>node_modules/</em>. To deliver them to client-side, we use <em>browserify-rails</em>, which bundles <em>node_modules/</em> content into Rails assets pipeline without requiring any configuration.</p><p>Add the gem and run ‘<em>bundle install</em>’:</p><pre># Gemfile</pre><pre>gem ‘browserify-rails’</pre><h4>Relay.QL and GraphQL Data Schema</h4><p>With Relay, for each React component in our client-side Javascripts, we create a RelayContainer counterpart to declare its data requirement:</p><pre>// app/assets/javascripts/relay/components/board.react.jsx</pre><pre>class BoardApp extends React.Component {<br>  render() {<br>    var _name = this.props.simple.name;<br>    return (<br>      &lt;div&gt;<br>        Boarding… {_name}<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><pre>var BoardRelayContainer = Relay.createContainer(BoardApp, {<br>  fragments: {<br>    simple: () =&gt; Relay.QL`<br>      fragment on Simple {<br>        name<br>      }<br>    `,<br>  },<br>});</pre><p>In the RelayContainer, there are Relay.QL fragments, which are NOT Javascripts, and needs to be transpiled based on the GraphQL data schema we defined at our GraphQL server.</p><p>Facebook provides the <em>babel-relay-plugin </em>to do the required transpilation, but it requires our data schema in JSON format as input. To convert our Ruby-based GraphQL schema in <em>app/graph</em> into a JSON file <em>(app/assets/javascripts/relay/data/schema.json</em>), use the Rails console:</p><pre># rails console<br>File.open(&#39;app/assets/javascripts/relay/data/schema.json&#39;, ‘w’) do |f|<br>  f.write(RelayOnRailsSchema.execute(<br>    GraphQL::Introspection::INTROSPECTION_QUERY).to_json<br>  )<br>end</pre><p>If you are using the starter-kit, just do:</p><pre># Command line</pre><pre>rake graphql:update_schema_json</pre><p>Create a new transpilation plugin by initializing <em>babel-relay-plugin</em> with the JSON schema file as shown in <em>app/assets/javascripts/relay/utils/babelRelayPlugin.js</em>:</p><pre>// app/assets/javascripts/relay/utils/babelRelayPlugin.js</pre><pre>var getBabelRelayPlugin = require(‘babel-relay-plugin’);</pre><pre>// load previously saved schema data<br>var schemaData = require(‘../data/schema.json’);</pre><pre>// create a plugin instance<br>var plugin = getBabelRelayPlugin(schemaData.data);</pre><pre>module.exports = plugin;</pre><h4>Transpile Relay.QL fragments</h4><p>Configure <em>browserify-rails</em> to perform transpilation (while doing bundling) in <em>config/application.rb</em>:</p><pre># config/application.rb</pre><pre>config.browserify_rails.commandline_options = ‘-t [ babelify --plugins “./relay/utils/babelRelayPlugin” ] --extension=”.react.jsx”’</pre><p>Note that the plugin we created from <em>babel-relay-plugin</em>, relies on <em>babelify</em>.</p><p><strong>NOTE</strong>: As bonus, <em>babelify</em> can also transpile JSX tags if they are used in our React components. However, <em>babelify</em> seems to do JSX transpilation only if your files have <em>.jsx</em> extension.</p><h4>Displaying the Relay/React App</h4><p>Prepare a Javascript snippet to render the RelayContainer (<em>BoardRelayContainer</em>) in <em>app/assets/javascripts/relay/boardapp.react.jsx</em>:</p><pre>// app/assets/javascripts/relay/boardapp.react.jsx</pre><pre>var BoardRelayStart = function() {<br>  ReactDOM.render(<br>    &lt;Relay.RootContainer<br>      Component={BoardRelayContainer}<br>      route={BoardRelayRoute}<br>    /&gt;,<br>    document.getElementById(‘board-id’)<br>  );<br>};</pre><pre>module.exports = BoardRelayStart;</pre><p>Make the <em>BoardRelayStart</em> function available. The simplest way is declaring it in <em>app/assets/javascripts/application.js</em>:</p><pre>// app/assets/javascripts/application.js</pre><pre>window.getBoardApp = require(‘relay/boardapp’);</pre><p>Lastly, deliver the UI to the user through a HTML page with a Javascript to call <em>BoardRelayStart</em> function in <em>app/view/static_pages/board.html</em>:</p><pre>// app/views/static_pages/board.html</pre><pre>&lt;div&gt;<br>  The Board!<br>&lt;/div&gt;<br>&lt;div id=’board-id’&gt;<br>&lt;/div&gt;</pre><pre>&lt;script&gt;<br>  window.getBoardApp();<br>&lt;/script&gt;</pre><p>The controller for this page is in <em>app/controllers/static_pages_controller.rb</em>:</p><pre># app/controllers/static_pages_controller.rb</pre><pre>class StaticPagesController &lt; ApplicationController<br> def board<br> end<br>end</pre><p>And its routes in config/routes.rb:</p><pre># config/routes.rb</pre><pre>scope ‘/static_pages’ do<br>  get “/board”, to: “static_pages#board”<br>end</pre><p>I hope you will find this Relay On Rails starter-kit useful! Let me know of any errors, suggestions, etc. @neth_6.</p><h3>Resources</h3><p><a href="https://facebook.github.io/relay/">Facebook Relay</a>: The source of authoritative information on Relay</p><p><a href="https://facebook.github.io/relay/docs/tutorial.html">Facebook Relay Tutorial</a>: I read this (&gt; 2 times start-to-end) to get started</p><p><a href="https://github.com/facebook/relay">Facebook Relay Github Repo</a>: The examples provide useful references for various GraphQL schema definitions, and client-side Relay Javascript and Relay.QL snippets</p><p><a href="https://github.com/nethsix/relay-on-rails">Facebook Relay Starter Kit</a>: If you are doing everything in Javascript, and have a preference to use <em>webpack</em> for Javascript bundling/transpilation, clone this to get started, or refer to it for <em>webpack</em> configuration</p><p><a href="https://github.com/mhart/simple-relay-starter">Simple Relay Starter Kit</a>: If you are doing everything in Javascript, and have a preference to use <em>browserify</em> for Javascript bundling/transpilation, clone this to get started, or refer to it for <em>brwoserify</em> configuration</p><p><a href="https://github.com/rmosolgo/graphql-ruby"><em>graphql-ruby</em></a> &amp; <a href="https://github.com/rmosolgo/graphql-relay-ruby"><em>graphql-relay-ruby</em></a>: The authoritative sources for defining GraphQL schema in Ruby GraphQL classes, and getting Rails to speak GraphQL.</p><p><a href="https://github.com/substack/node-browserify#usage"><em>browserify</em></a> documentation: Command-line options required to do transpilation, e.g., —plugin, etc.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b4af2057152" width="1" height="1" alt=""><hr><p><a href="https://medium.com/react-weekly/relay-facebook-on-rails-8b4af2057152">Relay/GraphQL On Rails</a> was originally published in <a href="https://medium.com/react-weekly">React Weekly</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Never `import React from ‘react’` again, thanks to Webpack’s ProvidePlugin]]></title>
            <link>https://medium.com/react-weekly/never-import-react-from-react-again-thanks-to-webpack-s-provideplugin-69e7feb69e?source=rss----955bdba6e52f---4</link>
            <guid isPermaLink="false">https://medium.com/p/69e7feb69e</guid>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Jennie Kim Eldon]]></dc:creator>
            <pubDate>Sat, 10 Sep 2016 20:26:56 GMT</pubDate>
            <atom:updated>2015-12-25T18:38:26.660Z</atom:updated>
            <content:encoded><![CDATA[<p>How many times a day do you write this import statement?</p><pre>import React from ‘react’</pre><p>Or this guy?</p><pre>import ReactDOM from ‘react-dom’</pre><p>A few weeks ago, a colleague at Udacity showed me a trick that eliminates the need for repetitive import statements in your code. The magic starts on line 18, with Webpack’s <a href="https://webpack.github.io/docs/list-of-plugins.html#provideplugin">ProvidePlugin</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e840dc30307109e2f8660a20f10346c4/href">https://medium.com/media/e840dc30307109e2f8660a20f10346c4/href</a></iframe><p>When Webpack builds your JavaScript, it will load the ‘react’ module whenever the identifier ‘React’ is declared in your code. So now you can use:</p><pre>React.createClass(…)</pre><p>…without having to import ‘react’ explicitly at the top of your component file.</p><p>Webpack’s ProvidePlugin isn’t limited to React dependencies, of course. You can use it to load all your frequently used modules.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4ecd81636efe24f4e6c9fe3a07c355b/href">https://medium.com/media/f4ecd81636efe24f4e6c9fe3a07c355b/href</a></iframe><p>This not only leads to fewer build errors, it also gets rid of big import blocks like this at the top of your code:</p><pre>import ReactDOM from ‘react-dom’<br>import _ from &#39;lodash&#39;<br>import $ from &#39;jquery&#39;<br>import cssModule from &#39;react-css-modules&#39;</pre><p>I feel an irrational amount of happiness about such things, don’t you?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69e7feb69e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/react-weekly/never-import-react-from-react-again-thanks-to-webpack-s-provideplugin-69e7feb69e">Never `import React from ‘react’` again, thanks to Webpack’s ProvidePlugin</a> was originally published in <a href="https://medium.com/react-weekly">React Weekly</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a React & MobX application with MVVM]]></title>
            <link>https://medium.com/react-weekly/building-a-react-mobx-application-with-mvvm-ec0b3e3c8786?source=rss----955bdba6e52f---4</link>
            <guid isPermaLink="false">https://medium.com/p/ec0b3e3c8786</guid>
            <category><![CDATA[mobx]]></category>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[babeljs]]></category>
            <dc:creator><![CDATA[Mattia Manzati]]></dc:creator>
            <pubDate>Sat, 10 Sep 2016 19:38:30 GMT</pubDate>
            <atom:updated>2016-08-29T17:07:38.449Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*gDZgHB7KYr44WG442p5BBw.png" /><figcaption>The resulting app we’ll build together!</figcaption></figure><p>Today, we’ll deep dive into building a full TodoEditor with MobX and React, starting from the basics and ending with some considerations.</p><p>Here you’ll find the entire code repo! <br><a href="https://github.com/mattiamanzati/react-mobx-todo-editor">https://github.com/mattiamanzati/react-mobx-todo-editor</a></p><h3>Finding a JavaScript editor</h3><p>First of all, you will obviously need any text editor to edit your JavaScript code. I recommend using <a href="https://code.visualstudio.com/">VSCode</a>, an OpenSource JavaScript editor supported by Microsoft. Give it a shoot, it’s great!</p><h3>Setting up the build environment</h3><p>Setting up the full stack build environment for a React application could be tedious, but fortunately facebook published a create-react-app package, which provides a fast and convinient way to create your React app and automatically setup <a href="http://www.babeljs.io/">Babel</a> and <a href="https://webpack.github.io/">Webpack</a>.</p><p>Now, after installing <a href="https://nodejs.org/en/">NodeJS</a> on our system, let’s install the create-react-app package globally by doing</p><pre>npm install -g create-react-app</pre><p>Notice: if you are running on Linux, you may need to prefix it with “sudo”.</p><p>Now we can create our project folder by running from the parent destination folder:</p><pre>create-react-app react-mobx-todo-editor</pre><p>After some dependencies are downloaded, a “react-mobx-todo-editor” folder will appear, and we’ll reference to it later as “project folder”.</p><p>Unfortunately the preset does’nt includes by default support to decorators, that we will use later to decorate class properties, so we need to “eject” the default configuration and edit that manually. To do so, simply run</p><pre>npm run eject</pre><p>inside of your project folder. That will result in a config and in a scripts directory being created. Let’s now install the Babel plugin to handle decorators:</p><pre>npm install babel-plugin-transform-decorators-legacy --save-dev</pre><p>now, we need to edit both “config/babel.dev.js” and “config/babel.prod.js” and add the decorators legacy transformer to the plugins array like this to let babel know about this additional transformer:</p><pre>plugins: [<br>    // handles @decorator<br>    require.resolve(&#39;babel-plugin-transform-decorators-legacy&#39;),</pre><p>Now, you can run</p><pre>npm run start</pre><p>to start the development server: a browser page will open showing a default React app.</p><p>You can also run</p><pre>npm run build</pre><p>to create the production build of your project! A “build” folder will appear containing the built files of your single page application.</p><p><strong>You can now clear the content of the “src” folder, as we will put there our application code.</strong></p><h3>Installing additional required packages</h3><p>Now we need to install mobx and mobx-react! To do so, simply type:</p><pre>npm install mobx mobx-react --save</pre><h3>Creating the domain models with MobX</h3><p>React and MobX are great libraries that allow to build a clean MVVM architecture in JavaScript.</p><p>Let’s now start by writing first our domain models, which in this example the only domain model is the “Todo” entity. We’ll create a “Todo.js” file in the “src” folder with the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d1f5a9a86c1f0ca98ae3e1ce795c4b3/href">https://medium.com/media/6d1f5a9a86c1f0ca98ae3e1ce795c4b3/href</a></iframe><p>To create a full working example, I added two serialize and deserialize methods, but keep in mind that you could use <a href="https://github.com/mobxjs/serializr">https://github.com/mobxjs/serializr</a> to easily define the model schema and serialize/deserialize it easily to JSON.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f53a1102dd93e014bca5a88169b49f09/href">https://medium.com/media/f53a1102dd93e014bca5a88169b49f09/href</a></iframe><h3>Creating the ViewModel in MobX</h3><p>You know, Model is’nt everything! You need somewhere to define the logic to interact with it! That’s what’s the ViewModel is for. ViewModel provides data and logic that will be used by the view to interact with domain models.</p><p>We will create a “TodoViewModel.js” file in the “src” folder with the content below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f89b0f73d7a8ac8d68cf7ead61016451/href">https://medium.com/media/f89b0f73d7a8ac8d68cf7ead61016451/href</a></iframe><p>As you can see, our view model is a simple list of todos, with methods to add and remove todos and save and load them form the browser <a href="http://www.w3schools.com/html/html5_webstorage.asp">LocalStorage</a>.</p><h3>Creating the React View</h3><p>Now we have all the data and methods to interact with… what’s missing? The View! To create the View we simply create <strong>React components that accepts a “model” prop which is an instance of our ViewModel</strong> and decorate them with “observer” from the “mobx-react” package.</p><p><strong>The observer will automatically force the view to update whenever an object given as prop to our component has changed observable properties.</strong> And that’s exactly our case; we want the view to automatically update whenever our ViewModel or our Model changes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3a4ff501ba619c90c28f470b588b372/href">https://medium.com/media/c3a4ff501ba619c90c28f470b588b372/href</a></iframe><p><strong>This way our view is completely decoupled from our logic.</strong> We could for example take advantage of this feature and <strong>create a React Native view using the same Model and ViewModel</strong> of the HTML one.</p><p>Notice that I have used classic React components class to improve readability, but you should use StatelessFunctionalComponents, as the data is coming in from the view model.</p><h3>Wiring it up</h3><p>Finally the last step is to wire up ViewModel and View, and proceed to render them. To do so, we simply create and “index.js” file in our “src” folder that imports the View and the ViewModel, creates a ViewModel instance and render the View with the given ViewModel instance.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fbcb8681d39b7df10abea0870048d466/href">https://medium.com/media/fbcb8681d39b7df10abea0870048d466/href</a></iframe><p>Now we run “npm run start” and our first React &amp; MobX Todo Editor is running!</p><p>If you’re ok with it, you can now simply run “npm run build” and serve the “build” folder content to an HTTP server!</p><h3>Make it prettier</h3><p>What your app to rock? We could use the <a href="http://www.material-ui.com/">MaterialUI</a> package components to make our todo app look nicer! You simply need to update your view to use the MaterialUI components package! First of all, let’s install the material-ui package:</p><pre>npm install material-ui react-tap-event-plugin --save</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*gDZgHB7KYr44WG442p5BBw.png" /></figure><p>Here’s the code to build it! You can find more components in the Material UI API docs!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e16f0823aa2905a60445d5979904460/href">https://medium.com/media/1e16f0823aa2905a60445d5979904460/href</a></iframe><p>you will also need to add these line to the start of “index.js” in order to support mobile devices tap event:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ec3c54fd9e25ac0e391500a17f3ad49/href">https://medium.com/media/6ec3c54fd9e25ac0e391500a17f3ad49/href</a></iframe><p>Now you are able to build larger application with React &amp; MobX; simply keep going creating Model, ViewModel and Views and wire them up. As occurs in other languages, you can use multiple ways to wire up the View and the View Model.</p><p>The easy one is to create a singleton of the ViewModel and simply pass it as property of the React component, as we did before.</p><p><strong>Another way, that avoids singleton,</strong> is to use the &lt;Provider/&gt; and connect() from the ‘mobx-react’ package, that allows to define a top-level provider which provides instances of the ViewModels and the Views will connect() to one of the provided ViewModels.</p><p>You could also check-out the <a href="https://github.com/mattiamanzati/mobx-mvvm/blob/master/examples/src/index.tsx">mobx-mvvm</a> package, which is an on-going experiment that provides not only a way to link View and ViewModels, but also <strong>provides a way to link the properties of the component to the properties of ViewModel automatically.</strong></p><p><a href="https://github.com/mattiamanzati/mobx-mvvm/blob/master/examples/src/index.tsx">Here you could find the same example of this post wired with mobx-mvvm.</a></p><p>Thanks for your time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec0b3e3c8786" width="1" height="1" alt=""><hr><p><a href="https://medium.com/react-weekly/building-a-react-mobx-application-with-mvvm-ec0b3e3c8786">Building a React &amp; MobX application with MVVM</a> was originally published in <a href="https://medium.com/react-weekly">React Weekly</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is React.js fast?
Faster than {framework}?
… or are there more relevant questions to be asking?]]></title>
            <link>https://medium.com/react-weekly/is-react-js-fast-faster-than-framework-or-are-there-more-relevant-questions-to-be-asking-bcf40211f89b?source=rss----955bdba6e52f---4</link>
            <guid isPermaLink="false">https://medium.com/p/bcf40211f89b</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Jeff Barczewski]]></dc:creator>
            <pubDate>Tue, 06 Sep 2016 00:35:45 GMT</pubDate>
            <atom:updated>2015-07-16T18:13:19.023Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qmhtum3UG8KqFTnr6EsuDw.jpeg" /></figure><p>I give training in React.js via <a href="http://codewinds.com/reactjs">CodeWinds</a>, and one of the questions I’m often asked is whether it is faster than X?</p><p><strong>The short answer is that React.js is very performant out of the box, even before you start tweaking.</strong></p><p>Note that performance is always a tradeoff and one needs to be careful to optimize real use cases (e.g. time to render moderately complex screen) instead of artificial benchmarks (reorder 1000 items).</p><p>Even so, React.js has a great performance story. Its component model lets you easily optimize performance bottlenecks without changing the components’ interface. You’re free to apply manual optimizations to specific parts of your app without changing your whole approach. So if you need them, additional optimizations are available.</p><p><strong>However, I don’t think those are even the best questions to be asking.</strong></p><blockquote>React.js is a pivotal technology that is moving the whole industry forward.</blockquote><p>Why is it such a game changer?</p><ul><li>Simplicity</li><li>Composable components</li><li>Declarative</li><li>Easy to use with existing projects</li><li>Functional / Immutable friendly</li></ul><p>Facebook’s success in breaking from the mold and embracing bold ideas has raised the bar for everyone. It takes a leader to blaze the trail and prove out a technology before the mainstream will even take notice. Fortunately Facebook has just such an engineering team and leaders who embrace sharing this openly with the world.</p><p>There are always going to be new libraries or frameworks that will come up optimized for specific use cases that will be knocking on the doors wanting to take the new performance crown. So we have to be careful to not get caught up in chasing that carrot. It’s a never ending battle.</p><blockquote>Performance does matter, but it’s only one of the factors to consider when choosing technology.</blockquote><p>With the fantastic teams at Google, Mozilla, and Microsoft improving JS engine performance month after month, benchmarks and performance are constantly changing. Something that was faster last month, might not be the leader in the next. Fortunately, most everything is moving forward since general engine performance is improving across the board.</p><p>Another thing to consider is how closely does that micro-benchmark match your workload? Unless you have a real world environment and are tracking actual usage, it is hard to even dream up the proper things to evaluate.</p><p>Some alternate questions which I think might be better to ask are:</p><p><strong>Developer Experience</strong></p><ul><li>Is React.js easy to learn so that my whole team can use it effectively?</li><li>How easy is it to evolve an existing code base? Not everyone is starting with fresh stack, so is it possible to ease into React.js or does it require a full rewrite?</li><li>How well do the React.js abstractions hold up when the codebase needs to be enhanced over time to support new features?</li><li>What type of Developer Experience (DX) does React.js provide?</li><li>What type of User Experience (UX) does React.js enable?</li></ul><p><strong>Stability &amp; Resilience</strong></p><ul><li>How reliable and solid is React.js? Are we going to be constantly chasing bugs or weird anomalies?</li><li>Is it battle proven and receiving enough adoption to trust? Likewise, a smaller project doesn’t have the means to chase down edge cases across the multitude of browsers in use.</li></ul><p><strong>Community</strong></p><ul><li>Is the community welcoming and supportive?</li><li>Is React.js and its community forward thinking? Is it looking at the best ideas in the industry and moving towards those goals?</li></ul><p>I think these types of questions are possibly more relevant to consider than the performance one.</p><p>… And I believe React.js nails it on every one of these.</p><blockquote>In fact, it would be hard to find a UI library that has a better story than React.js with regards to all these key questions.</blockquote><p>Even if we go back to the original performance question, React.js has an excellent position. Yes, it is very performant out of the box for the common use cases, but if necessary developers can tap into even more optimizations like shouldComponentUpdate and perhaps using immutable data structures to squeeze out additional speed. Without adding prohibitive complexity, developers have the confidence that they can optimize slow parts of their app if and when real use indicates performance enhancements are necessary and justified.</p><p><strong>In my opinion, Facebook and the React.js community have set a new bar for UI development</strong>, one that now extends into mobile apps and all variety of devices (desktop, set top, …) as well. I believe history will hold a special place for this little UI library.</p><blockquote>So be a part of the revolution. Join the React.js community. I think you’ll love it.</blockquote><p>Some resources to get started with React.js</p><ul><li><a href="http://facebook.github.io/react/">Main React.js site</a> contains some great articles to get you started.</li><li><a href="http://codewinds.com/reactjs">CodeWinds</a> has continuing coverage of React.js and will host my forthcoming video course on React.js due this summer. Subscribe to be notified when it is available.</li></ul><p>Many thanks to those that reviewed my article and provided feedback</p><ul><li>Kevin Old <a href="https://twitter.com/kevinold">@KevinOld</a></li><li>Jed Watson <a href="https://twitter.com/jedwatson">@JedWatson</a></li><li>Dan Abramov <a href="https://twitter.com/dan_abramov">@Dan_Abramov</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bcf40211f89b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/react-weekly/is-react-js-fast-faster-than-framework-or-are-there-more-relevant-questions-to-be-asking-bcf40211f89b">Is React.js fast?
Faster than {framework}?
… or are there more relevant questions to be asking?</a> was originally published in <a href="https://medium.com/react-weekly">React Weekly</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Code Chunking with Webpack — A pragmatic approach]]></title>
            <link>https://medium.com/react-weekly/code-chunking-with-webpack-a-pragmatic-approach-e17e8bcc6453?source=rss----955bdba6e52f---4</link>
            <guid isPermaLink="false">https://medium.com/p/e17e8bcc6453</guid>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[chunking]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Param Singh]]></dc:creator>
            <pubDate>Mon, 05 Sep 2016 15:37:25 GMT</pubDate>
            <atom:updated>2016-09-06T18:21:45.525Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*s7zJmbewKLwHfGnyxQleCw.jpeg" /></figure><p>Ever since the inception of client side JS taking control of the web, we have observed a hefty amount of JS being written or included in our web apps. Gone are the times when our servers used to render the html for our web apps (although they’re used for <a href="http://redux.js.org/docs/recipes/ServerRendering.html">initial server side rendering</a>). Today we need more out of our web apps like lazy loading of data through Ajax, cool animations, app state management, routing, infinite scrolling and many more.</p><p>All of these things mentioned require a decent amount of work on JavaScript by a front-end developer. The result is a huge pool of JS files since developing for front-end requires being dependent on some library or framework or at least jQuery. Writing all of your code in VanillaJS is not everybody’s cup of tea. Besides this, you also tend to keep your code modular using <a href="https://www.wikiwand.com/en/Design_Patterns">design patterns</a> namely modular pattern, factory pattern, singleton pattern, observer pattern etc. These things takes an important place in development. I can’t imagine engineering a complex web app without the use of such design patterns.</p><p>Now, while maintaining a modular code is beneficial for development purpose but not ideal for your production environment. It’s a very crucial step in web optimisation to bundle up all your files into one before deploying on production. Why? because generating individual http network request for all those modular files is not efficient. Running 1 request for a bundled file over 100 requests to fetch 100 files is more efficient. So, as you can see there’s a trade off kinda situation between the two approaches. The latter approach can provide you with things like lazy loading of modules on demand but results in a lot of network requests. The former approach does efficiently single request and reduces frequent roundtrips to the server but at the same time takes a heavy toll on the initial load time. The <a href="https://developers.google.com/web/fundamentals/performance/critical-rendering-path/?hl=en">CRP</a>(Critical Rendering Path) of your web app should not involve long blocking Javascript as it might block your initial load time giving a bad experience to your first time users and even worse on a slow network.</p><p>So, one thing is clear that we just have to bundle up the JS files for production while keeping the initial load time low. Then how can we break this deadlock? The answer is <a href="https://webpack.github.io/docs/code-splitting.html">Code Splitting or Chunking</a> i.e we can find a middle ground between these two things by <strong>increasing the number of requests while keeping them bundled</strong>.</p><p>My discussion will follow my favourite bundling tool <a href="https://webpack.github.io/"><strong>webpack</strong></a>. But this concept of chunking is there in all other bundlers like <a href="http://browserify.org/">browserify</a>, <a href="http://requirejs.org/docs/optimization.html#onejs">requirejs</a> or <a href="https://github.com/requirejs/almond">almondjs</a>. Coming back to the discussion, for most of our web apps we have two kind of codes, one which is written by us and the other on which we depend or the third party libs you can say. Now, its wise to separate them apart firstly. Reason I’ll tell you shortly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xyajIrA0G67H3Y1GEsUocg.png" /><figcaption>Before Segregation</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dN3HnBuHCP6rcN81gJKx4Q.png" /><figcaption>After Segregation</figcaption></figure><p>Above are the two illustrations of my bundled file sizes before and after chunking. As you can see my index.js has size of 666 kB(after minification) in the first screenshot and when I moved all my vendor or 3rd party code to vendor.js it became 1.1 MB + 172 kB. This inflation is because I have included the whole <a href="http://material-ui.com/">Material UI</a> library for my react project instead of individual components as in the first case. But lets not deviate out discussion on that. Sticking to the point, we have successfully finished the first phase of chunking.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7461d8aeb29c323b3cdbcd9a8710ee89/href">https://medium.com/media/7461d8aeb29c323b3cdbcd9a8710ee89/href</a></iframe><p>Lets, do a bit more. Lets say I wanna cache this vendor.js on user’s client machine for a longer period of time using maybe service worker, server side caching or through shipping it along with my Android app build as I do at my current job. The point is, our vendor.js is not going to change that frequently as compared to my own written code in the form of index.js. Moving on, we have to do versioning to make sure our vendor.js file doesn’t change overtime. Also for generating a hash based content for our vendor.js, we’ll need to separate our webpack runtime code from it into say meta.js or init.js. See this <a href="https://github.com/webpack/webpack/issues/1315#issuecomment-155100976">github issue</a>. The result will look something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9zS7NNaaujLS8Vl2k4oa5A.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7f6b5731159ff719428c7e3b247f349/href">https://medium.com/media/c7f6b5731159ff719428c7e3b247f349/href</a></iframe><p>Also, to make your vendor.[chunkhash].js fully static, please use this new webpack NamedModulesPlugin since it uses the names of module files instead of dynamically generated files during bundling. These are all little caveats I figured out while working with webpack.</p><p>Cool, so far we have separated the runtime from our vendorjs, content based automated versioning has been done. Our build files are ready for caching. Only one teensy things left, infact the main challenge, how will we include these dynamically generated hashed filenames into my index.html?? Don’t worry, there exists a webpack <a href="https://github.com/ampedandwired/html-webpack-plugin">HtmlWebpackPlugin</a> that’ll exactly solve this problem. You can use it like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/39dde60a27aba853be7a2fdd82d29657/href">https://medium.com/media/39dde60a27aba853be7a2fdd82d29657/href</a></iframe><p>As you can see I’m using an ejs template for generating my index.html file. You can skip that and set your inject option as true which will automatically inject the generated js files in the end before the closing body tag. My requirement was different since I had to embed my versioned files in a Django template which already has {{}} reserved, otherwise I could had used moustache or handlebars. You can checkout more options on <a href="https://github.com/ampedandwired/html-webpack-plugin">HtmlWebpackPlugin</a> docs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/54ac3106332edd87a8cb70d4e8219a37/href">https://medium.com/media/54ac3106332edd87a8cb70d4e8219a37/href</a></iframe><p>Voila! We just accomplished transforming our web app ready for caching 3rd party vendor.[chunkhash].js. Now, all that will change overtime is index.[hash].js. So, 90% of the load time has been already reduced for subsequent page loads on users machine as the hash of the vendor file will remain same through out. Now, all that we need to focus is on index.[hash].js which is 172 kB in our case. We can further break this into chunks and load them on demand on events like route change most commonly.</p><p>Lets try it out with react-router. React Router allows you to add hooks to routes before navigating. So what you can do is specify the load of a certain module using <a href="https://github.com/reactjs/react-router/blob/master/docs/guides/DynamicRouting.md">require.ensure</a> or <a href="http://moduscreate.com/code-splitting-for-react-router-with-es6-imports/">System.import</a> with webpack 2. Lets stick to the former one.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1dcf3edd65dfe1485200a96acd7be32a/href">https://medium.com/media/1dcf3edd65dfe1485200a96acd7be32a/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91ffeb12f461d36ccfcf5afecc6195f6/href">https://medium.com/media/91ffeb12f461d36ccfcf5afecc6195f6/href</a></iframe><p>Above is the implementation of lazily loading the route. On a side note, I tried abstracting the getComponent handler function but for some bizarre require context reasons it wasn’t accepting dynamic params from the closure (If you can solve it, please go ahead and let me know as well). Anyway, lets see run the webpack and analyse the output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2SdXmT20pNnmshOD6Lip9w.png" /></figure><p>The size of the index.[hash].js has reduced from 173 kB to 113 kB. There’s a straight ~35% or reduction in its size, so you can pretty much expect quicker initial load than before. And as you navigate to a certain route, the corresponding chunk will be load <em>lazily </em>on demand.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*Nbnrc3HOtyZg49TCeQtowA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*h3LczKjk8HuLu3PmkGZ3og.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*sogbqJPjqch6nMoPwqmz4w.png" /><figcaption>Dynamic loading of chunks based on routes</figcaption></figure><p>Phew! That was tiring. Was it? You decide. But in the end of the day your app users will be happy which is makes our efforts worthy. So, go ahead and transform your web app taking these amazing advantages webpack offers you to put a smile on your app users face.</p><p><strong>Summary</strong></p><p>So, we learnt about why bundling is important, how to separate your vendor and your own app code to implement caching, versioning your files for proper <a href="http://webassets.readthedocs.io/en/latest/expiring.html"><strong>cache busting</strong></a>. I’m sure you might have got stuck in a situation like “I have deployed my latest code on server, but still I’m getting the old version on my app”. Webpack automated versioning we learnt can help you alleviate such pains (things like index.js?v=2). After that, our separated index file of 173 kB was reduced to 113 kB using lazy loading with react-router.</p><p>I hope you liked my post. I thoroughly enjoyed writing it and in fact learnt few things while writing it. If you do too, please recommend and comment.</p><p>Thank You!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e17e8bcc6453" width="1" height="1" alt=""><hr><p><a href="https://medium.com/react-weekly/code-chunking-with-webpack-a-pragmatic-approach-e17e8bcc6453">Code Chunking with Webpack — A pragmatic approach</a> was originally published in <a href="https://medium.com/react-weekly">React Weekly</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Embracing Immutable Architecture]]></title>
            <link>https://medium.com/react-weekly/embracing-immutable-architecture-dc04e3f08543?source=rss----955bdba6e52f---4</link>
            <guid isPermaLink="false">https://medium.com/p/dc04e3f08543</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[immutable-infrastructure]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Ryan C. Collins]]></dc:creator>
            <pubDate>Sun, 04 Sep 2016 21:53:38 GMT</pubDate>
            <atom:updated>2016-09-11T19:11:06.957Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*De-cn--751z3cHRlMiXJDw.png" /><figcaption>Diagram of Immutable Architecture from Lee Byron’s Talk</figcaption></figure><p>I believe as a community, many of us JavaScript engineers have embraced Immutable Architecture. Whether we realize it or not, a new way of building apps has crept into the mainstream JavaScript ecosystem and it is here to stay.</p><h3>What is Immutable Architecture, anyways?</h3><p>To understand immutable architecture, we need to first understand state. State, an evil source of complexity in any software, is the characteristic of a value. According to Miriam Webster, state is defined as “the particular condition that someone or something is in at a specific time.” As we continue to make web applications with more and more dynamic data, we are introducing more and more state into our applications.</p><p>Combined with asynchronicity, a core characteristic of modern web applications, it’s no wonder why our applications have become very hard to understand.</p><p>Whether you realize it or not, you have most definitely dealt with state bugs many times over if you are a software engineer in any capacity. In fact, there is a famous white-paper about the <a href="http://www.curtclifton.net/storage/papers/MoseleyMarks06a.pdf">Software Crisis</a> that references state as the number one contributor to software complexity.</p><p>The main issue with state complexity is that it causes our code to become harder to reason about. When you are unable to reason about what your code is doing, you lose the ability to properly communicate with the computer and that leads to bugs and the inability to maintain the software. As software scales to more and more people, the probability of introducing state bugs increases exponentially.</p><p>So how do we control state complexity? It’s actually really simple, we use <a href="http://www.dictionary.com/browse/immutability">Immutability</a> to our advantage.</p><h3>Immutability</h3><p>Immutability is defined as “unchanging over time or unable to be changed.” In software, a value that is immutable, by its very definition, does not have state! With one simple change, our entire problem is solved! Where the complexity sinks back in is when you try to do anything meaningful without stateful data and the ability to mutate data.</p><p>It is a common misconception that immutability hinders the engineer’s ability to write meaningful software. Without going into the details of the mathematical background of Functional Programming, I am going to attempt to explain immutable architecture in simple terms that hopefully all of us can understand.</p><h3>State Management</h3><p>The way we curtail software complexity in JavaScript land is to use a state management library, such as <a href="https://www.google.com/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=3&amp;cad=rja&amp;uact=8&amp;ved=0ahUKEwis89j1xvHOAhUCQCYKHT4VDccQFggwMAI&amp;url=http%3A%2F%2Fredux.js.org%2Fdocs%2Fintroduction%2F&amp;usg=AFQjCNHnkPrMBLcMU_jNH47oP3RaS8JSqg&amp;sig2=19FujZxWZVBNUE6VBj_NeQ">Redux</a> or <a href="https://github.com/mobxjs/mobx">MobX</a>. One can also use any number of Immutable data structure libraries, but let’s leave that aside for now. With state management, what we are attempting to do is to handle the changing values over time (state mutations) through a predictable mechanism. In other words, the only way to alter state is through a strict mechanism.</p><p>In the case of <a href="https://github.com/reactjs/redux">Redux</a>, we use pure functions to mutate state. Pure functions are defined as those that given the same input, always return the same output. In other words, they are predictable as they do not rely on any outside mechanism or global state.</p><p>By employing state management in our apps, we are boldly turning off mutable state within the majority of our app and we are using state management to manage the situations where our state needs to be changed in order to provide a meaningful experience to our application’s end users.</p><p>I hope you see that this idea is fundamentally simplistic in nature. You do not need to be a functional programming wizard to understand it. State management needs to be a primary focus of all of our applications going forwards.</p><h3>One way data flow</h3><p>I am sure you have no doubt heard of <a href="http://redux.js.org/docs/basics/DataFlow.html">unidirectional data flow</a> by now. It is a natural extension of the ideas described above. With unidirectional data flow, we take the principles of pure functions and apply it to our entire app.</p><p>So now, our state is managed properly, we are using immutability throughout our app and our application consists almost entirely of pure functions. By thinking of our applications as a pure function of state, we are suddenly able to reason about what the application is doing. This can be applied to our entire application architecture, from data-fetching to UI.</p><p>A perfect example of this in practice is <a href="https://facebook.github.io/react/">React</a>. With React, you design your user interface as a collection of components. Each component is a pure function that takes data and returns HTML. With unidirectional data flow, we are able to describe our application as <a href="https://medium.com/@housecor/react-stateless-functional-components-nine-wins-you-might-have-overlooked-997b0d933dbc#.wsv7amxfq">pure functions</a> and we are given the guarantee that when the data changes in our app, through a predictable state management mechanism of course, the user interface will be completely recalculated.</p><p>Suddenly, we are given a guarantee that if our UI renders correctly once, it will render the same from now until eternity. The components of your application are now totally decoupled from the complexity of your app. This makes testing, both manual and automated, a predictable process.</p><p>Even without React, this concept can be applied to building applications in any domain. In fact, React is not at all necessary for this equation. Many frameworks are picking up these concepts and the newer version of JavaScript enable these ideas by having declarative mechanisms built right into the language.</p><h3>Paradigm Shift</h3><p>The transition to Immutable architecture represents a paradigm shift in our industry. Those of us that are using Immutable architecture on a daily basis are here to stay. Our software development process is just so much easier and less buggy. It scales well because it eliminates the biggest cause of software complexity, which again is the complexity caused by mutative state.</p><p>It is exciting to see the growing popularity of Immutable architecture. Elm, a functional language that compiles to JavaScript, was the first mainstream example of immutable architecture in Front End land. The fact that this same architecture was transferred, via Redux, to the mainstream JavaScript community is really fantastic. I think we owe a lot of credit to <a href="https://github.com/gaearon">Dan Abramov</a>, <a href="https://github.com/leebyron">Lee Byron</a> and the other incredible Facebook engineers for helping to lead the movement.</p><p>Over the last year, I have become immersed in Immutable architecture, both with Elm and JavaScript and I am happy to say that it will be the only architecture I use for the foreseeable future. There really is no going back for me. If you feel the same way, I would love to hear about your experience!</p><h3>More Resources</h3><p>If you have yet to embrace immutable architecture, I recommend the following resources.</p><ul><li><a href="https://vimeo.com/166790294">Talk by Lee Byron on Immutable Architecture</a></li><li><a href="http://redux.js.org/docs/introduction/Motivation.html">Motivation behind Redux</a></li><li><a href="https://github.com/MostlyAdequate/mostly-adequate-guide">Mostly Adequate Guide to Functional Programming in JS</a></li><li><a href="https://www.cs.cmu.edu/~rwh/theses/okasaki.pdf">Purely Functional Data Structures</a>— Not for the feingt of heart, but a fantastic source of information about persistant immutable data structures.</li><li><a href="https://www.oreilly.com/ideas/an-introduction-to-immutable-infrastructure">Immutable Infrastructure in Cloud Computing</a></li></ul><p>Also, searching for <a href="https://medium.com/search?q=immutable%20architecture">Immutable Architecture</a> and <a href="https://medium.com/search?q=functional%20javascript">Functional JavaScript</a> on Medium provides dozens of fantastic articles on the subject.</p><p>Please click the like button if you enjoyed this!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*prif7-04oPf8Dqo1gvSDsQ.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc04e3f08543" width="1" height="1" alt=""><hr><p><a href="https://medium.com/react-weekly/embracing-immutable-architecture-dc04e3f08543">Embracing Immutable Architecture</a> was originally published in <a href="https://medium.com/react-weekly">React Weekly</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>