<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Lin Clark on Medium]]></title>
        <description><![CDATA[Stories by Lin Clark on Medium]]></description>
        <link>https://medium.com/@linclark?source=rss-d3391efe481a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*vklXlk8XnKVUtJhuhOtMQQ.jpeg</url>
            <title>Stories by Lin Clark on Medium</title>
            <link>https://medium.com/@linclark?source=rss-d3391efe481a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 28 May 2026 00:14:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@linclark/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com" rel="hub"/>
        <item>
            <title><![CDATA[A cartoon guide to Facebook’s Relay, part 4]]></title>
            <link>https://medium.com/code-cartoons/a-cartoon-intro-to-facebook-s-relay-part-4-aef7d819a8ed?source=rss-d3391efe481a------2</link>
            <guid isPermaLink="false">https://medium.com/p/aef7d819a8ed</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[tech]]></category>
            <dc:creator><![CDATA[Lin Clark]]></dc:creator>
            <pubDate>Wed, 27 Jan 2016 13:47:35 GMT</pubDate>
            <atom:updated>2016-01-27T13:55:02.839Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GZx2kIRuPIJbmum6yYrTzA.gif" /></figure><p>So far you’ve seen how:</p><ol><li>Relay lets you say what data you need with GraphQL in <a href="https://code-cartoons.com/a-cartoon-intro-to-facebook-s-relay-part-1-3ec1a127bca5">part 1</a></li><li>Relay fetches data from the server in <a href="https://code-cartoons.com/a-cartoon-intro-to-facebook-s-relay-part-2-d4a2435aee59">part 2</a></li><li>Relay syncs changes back up to the server in <a href="https://code-cartoons.com/a-cartoon-intro-to-facebook-s-relay-part-3-9d8fcf8db670">part 3</a></li></ol><p>Now let’s see how all the different parts work together.</p><h3>Caveat: this is only an approximation</h3><p>In the cartoons up until now the scale of the diagrams has been 1:1… each arrow has (pretty much) represented a single function call.</p><p>For these diagrams, the scale is closer to 1:100. This is because Relay is doing so much for you.</p><p>Flux is a pattern. Relay is a framework. Flux just gives you guidelines on how to structure your application. Relay gives you concrete functionality. And lots of it.</p><p>This means that the number of different parts in the system has ballooned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*APMinvfY_aKeypSFA0To7g.png" /></figure><p>From the diagrams, it could look like implementing something with Relay requires a lot more work. The truth is, these extra characters take care of a lot of work for you. They are responsible for the magic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*qPgvIxYs06P7k2DfNGvXiA.png" /><figcaption>Magic!</figcaption></figure><p>You don’t really need to know every detail of what they do. In fact, there’s only a small number of parts that you even need to be aware of.</p><p>But cracking things open and seeing how they work is the fun part! So I’m going to try to give you a rough approximation of Relay’s inner workings.</p><h3>The chorus line of characters</h3><p>Even leaving out some of the lesser cast members, there are still a bunch of them. In my head, I divide them into 4 groups.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*XCwD3sllb682KhwFpy-cYQ.png" /></figure><h4>The user interface</h4><p>The user interface takes the data from the system and makes it understandable to the user. It also gives the user a way to change that data. It takes user input and turns it into something the system understands.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*AfR-MwAl1WdGBkOzy0USRA.png" /></figure><p>The parts of the user interface are:</p><p><strong>The root container </strong>— Kind of like the root component in <a href="https://code-cartoons.com/a-cartoon-intro-to-redux-3afb775501a6#.y9y398wyc">Redux</a>, the root container is a CEO. It chooses the top level component to use for the page. It also tells the app where in the graph to start the query. But after that, it’s pretty hands off.</p><p><strong>Containers </strong>—<strong> </strong>The container is like a project manager for the component. It has a list of all of the data the component needs to do its job. The container is on top of getting the data from the rest of the system. This allows the component to focus on its job.</p><p><strong>Components</strong> — A component in Relay is pretty much the same as it is in Flux. It is a presenter. It just knows how to format data into output that people understand (via HTML).</p><p><strong>Relay Renderer</strong> — In some ways, the Relay Renderer is like the view layer binding from Redux. Like an IT department, it hooks up the container to the store.</p><p><strong>Mutations</strong> —You saw mutations in <a href="https://code-cartoons.com/a-cartoon-intro-to-facebook-s-relay-part-3-9d8fcf8db670#.uzi8nc59z">part 3</a>. They are like action creators in Flux, but they do more. They provide blueprints for the mutation system to follow for different user changes.</p><h4>Data storage</h4><p>Data storage is handled by the store. Even though I’m only representing it as one character here, there are many different objects involved.</p><p>The UI talks to it whenever it wants data. It works with the query and mutation systems to make sure it has the data that the UI needs. The store also has a notification system. Each component gets custom-tailored updates when data it uses changes. The store handles all of the details of wiring up these notifications, so you don’t have to think about it.</p><h4>The query/mutation systems</h4><p>The query and mutation systems prepare queries. They also keep track of what queries have gone out and what data needs to come in for a query to be complete. You met them in <a href="https://code-cartoons.com/a-cartoon-intro-to-facebook-s-relay-part-2-d4a2435aee59#.iigb26u49">part 2</a> and <a href="https://code-cartoons.com/a-cartoon-intro-to-facebook-s-relay-part-3-9d8fcf8db670#.uzi8nc59z">part 3</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*980G74IU-tbd0JuhpPPKNQ.png" /></figure><h4>The cloud</h4><p>Two characters sit on either side of the cloud: the server on one side and the network layer (which is on the client) on the other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*-tiGTyGsbc8KVsCQcn8APg.png" /></figure><p><strong>The server </strong>— As you saw in <a href="https://code-cartoons.com/a-cartoon-intro-to-facebook-s-relay-part-1-3ec1a127bca5#.ignn4bn99">part 1</a>, the GraphQL server is like a librarian. It isn’t the library; it doesn’t actually store the information. You tell the GraphQL server what information you need, and it figures out where to go in the stacks to get that information for you.</p><p><strong>The network layer</strong>—The network layer manages all communication with the server. It is like an operator in The Matrix. It is responsible for getting requests into the cloud and making sure responses get out of the cloud. If the response doesn’t come out of the cloud correctly, the operator will retry twice before pulling the plug. It also handles errors.</p><h3>The first render</h3><p>Let’s see what happens when your app is first loaded.</p><h4>Step 1: Starting the process</h4><p>When the page is loaded, React starts rendering. The first thing it reaches is the root container. The root container passes off responsibility to Relay Renderer.</p><p>Relay Renderer is in charge of making sure the data is available to the UI. But because the app isn’t mounted, it knows that none of this data is available. It tells the store to start priming the cache.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*oMdXn8jKuvPB5YdaWn2u5A.png" /></figure><h4>Step 2: Priming the cache</h4><p>The store needs to know what data to get for the cache. Relay Renderer figures out what the starting point for the query is (the query root) and passes it to the store. It also gives the store a callback.</p><p>The store passes those off to the query system. Then the query system works with the store to figure out what data is already in the cache. We looked at this in <a href="https://code-cartoons.com/a-cartoon-intro-to-facebook-s-relay-part-2-d4a2435aee59#.iigb26u49">part 2</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*_VV4gE4TzRHSxIejz7fJ3g.png" /></figure><h4>Step 3: Building the query</h4><p>The query system builds the query.</p><p>I didn’t show this in <a href="https://code-cartoons.com/a-cartoon-intro-to-facebook-s-relay-part-2-d4a2435aee59#.iigb26u49">part 2</a>, but the query system talks to the containers here. It asks them what data they need. Each container passes off a query fragment which specifies the data its component needs.</p><p>The query system stitches together the full query out of all of these fragments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*QYJ2_LfrXe-jEB14TuvBRA.png" /></figure><h4>Step 4: Trimming down the query and queuing it up</h4><p>As we saw in <a href="https://code-cartoons.com/a-cartoon-intro-to-facebook-s-relay-part-2-d4a2435aee59#.iigb26u49">part 2</a>, the query system removes pending requests from the query. Then it adds the query to the queue of requests for the network layer to send out (and also adds it to its own list of pending requests).</p><p><em>Note: things start to go a little asynchronous here. I don’t have a good way to show this in the diagrams.</em></p><p>The query system is done with it’s work for now. It queues up a message for the Relay Renderer with the ready state. But first, the network layer needs to do it’s job…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*IpjexbquNEY2JoqC11EoCg.png" /></figure><h4>Step 5: Sending the query to the GraphQL server</h4><p>The network layer picks up the queue of requests that the query tracker left for it. It sends the requests off to the GraphQL server.</p><p>The network layer has nothing else to do ‘til the server responds. It lets the rest of the system do its thing while it waits.</p><p>The message that the query system put in the queue is sent. The Relay Renderer gets the ready state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*mAP5QUoxZ5mwM_HC5lKmYw.png" /></figure><h4>Step 6: Getting the data back and writing it to the cache</h4><p>The network layer hears back from the GraphQL server. It transforms the response to JSON. Then the query system picks it up and passes it off to the store. The store adds it to the local cache.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*mNbA1Roku_1J3m0CUyEkUw.png" /></figure><h4>Step 7: Notifying the renderer</h4><p>Once the data is written to the cache, the query system is notified. It sends out the message to Relay Renderer with a new ready state, letting the Renderer know that the cache is primed and ready to go.</p><p>Relay Renderer will then prepare an object that the containers can use to get their data from the store. It calls <em>setState()</em>, passing this object down to the containers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*K0-x2byai3EbkSDKaFKdBA.png" /></figure><h4>Step 8: Getting the data from the store to the UI</h4><p>Using the object that Relay Renderer passed down, the container will set up a “resolver”. It will use the resolver to get its data from the store.</p><p><em>Note: This is handled automatically in the container prototype’s </em>componentWillMount()<em> implementation.</em></p><p>During this process, the store also sets up some observers. These observers will notify the resolver, which will notify the container, whenever this data has changed.</p><p>Now that the container has the data, it calls <em>setState()</em> to pass it down to the component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*pr2xCXzWWM1Bnpl6inQYlw.png" /></figure><p>So that’s how I think about all the different parts of Relay. Hope it helps!</p><blockquote>Did this help? If it did, a click on the ♥ is much appreciated… it helps other people find it, too!</blockquote><figure><a href="https://leanpub.com/codecartoons-react"><img alt="" src="https://cdn-images-1.medium.com/max/600/1*b4pDY7WpzfoGJ2IeRnSiYQ.png" /></a></figure><figure><a href="http://tinyletter.com/codecartoons"><img alt="" src="https://cdn-images-1.medium.com/max/250/1*Vhx6UMeHXRPAEOGaPq8vQA.png" /></a></figure><figure><a href="https://twitter.com/codecartoons"><img alt="" src="https://cdn-images-1.medium.com/max/250/1*_oQtFJQYeeOkz4T81Sg4dA.png" /></a></figure><h3>Resources</h3><ol><li><a href="http://graphql.org/">GraphQL docs</a></li><li><a href="https://facebook.github.io/relay/docs/getting-started.html">Relay docs</a></li><li><a href="https://youtu.be/9sc8Pyc51uU">Talk at React.js Conf January 2015</a></li><li><a href="https://www.youtube.com/watch?v=_9RgHXqH8J0">Exploring GraphQL</a></li><li><a href="http://softwareengineeringdaily.com/2015/09/19/graphql-and-relay-with-nick-schrock/">GraphQL and Relay with Nick Schrock</a></li><li><a href="https://blog.jacobwgillespie.com/from-rest-to-graphql-b4e95e94c26b">From REST to GraphQL</a></li><li><a href="https://devchat.tv/adventures-in-angular/043-aia-falcor-with-jafar-husain">Falcor with Jafar Husain</a></li><li><a href="https://www.youtube.com/watch?v=IrgHurBjQbg">Relay: An Application Framework for React</a></li><li><a href="https://www.youtube.com/watch?v=Pxdgu2XIAAg">Scaling UI Development with Relay</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aef7d819a8ed" width="1" height="1" alt=""><hr><p><a href="https://medium.com/code-cartoons/a-cartoon-intro-to-facebook-s-relay-part-4-aef7d819a8ed">A cartoon guide to Facebook’s Relay, part 4</a> was originally published in <a href="https://medium.com/code-cartoons">Code Cartoons</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A cartoon guide to Facebook’s Relay, part 3]]></title>
            <link>https://medium.com/code-cartoons/a-cartoon-intro-to-facebook-s-relay-part-3-9d8fcf8db670?source=rss-d3391efe481a------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d8fcf8db670</guid>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Lin Clark]]></dc:creator>
            <pubDate>Mon, 25 Jan 2016 16:31:18 GMT</pubDate>
            <atom:updated>2016-01-27T13:56:57.299Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KaoKlN1wO7lqMbGsTajA0Q.gif" /></figure><p>Relay is the same as Flux and Redux in a way. All three of them use objects to represent changes. When a change object comes through to the store, the store will make the change in the state. Then the store will notify the UI to update.</p><p>Unlike Flux and Redux, Relay pushes the change up to the server, too.</p><p>Sometimes changes aren’t simple, though. They can ripple out and have effects that aren’t so obvious.</p><p>For example, take adding new content. It could have impacts on other parts of the graph, too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*9f--En1SSimSHSF3OyoANA.png" /><figcaption>The thick outline indicates the part of the graph that is being used in the browser. The rest is only on the server.</figcaption></figure><h4>Balancing speed and consistency</h4><p>How do you 1) show all of the changes, but 2) do it as quickly as possible?</p><p>To show all the changes, you could just refetch the whole graph… but that would be slow. Or you could just fetch the one change you made… but then the data isn’t consistent with what’s on the server.</p><p>Relay balances these two — speed and consistency. It does that by figuring out exactly what data it needs to update.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*ShpuhECZt9afTRsKmvHB8Q.png" /></figure><p>It will also make the change seem to happen faster by doing an “optimistic update”. This is where the app guesses what the new state will be before the server responds. When the server response does come in, it will make any necessary changes.</p><p>Here’s the sequence of events:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*rXvgXaqrjnczaQ9rBnuFqw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*387bhD5MA1sdc2QgGPM6EA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*HcJ2yb4QCbHjk-7BcYeGlg.png" /></figure><p>1. Relay updates the local cache with what it <em>thinks</em> the new state is going to be (an “optimistic update”… I’ll explain how it figures this out later).</p><p>2. It sends up the mutation query to the server. It also sends a query graph that requests data from the server. Once the server makes the update, it will fill in that query graph and return it as the payload.</p><p>3. The store will merge the payload into the graph it already has cached. If the optimistic update in step 1 was incorrect, those changes will be overwritten here.</p><p>Relay manages all this by introducing another new system, the mutation system.</p><h3>Introducing mutations &amp; the mutation system</h3><p>Mutations are the Relay version of the actions you see in <a href="https://code-cartoons.com/a-cartoon-guide-to-flux-6157355ab207">Flux</a> or <a href="https://code-cartoons.com/a-cartoon-intro-to-redux-3afb775501a6">Redux</a>. Instead of having an action type that comes from a list of constants, the Relay mutation has a name which comes from the list of mutations the server understands.</p><p>A mutation object knows its mutation name. And, like an action creator, it knows how to prepare the input… the variables the server will need to make the change.</p><p>But it does more than an action creator in Flux or Redux does.</p><h4>The mutation</h4><p>I think of the mutation as an architect. It provides a set of blueprints for different things.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*mwXoJeERRFgLt0C3wQM79Q.png" /></figure><p>It provides a blueprint for the fat query. This is a list of the fields that might change in response to the mutation. It can also provide a blueprint for optimistic updates.</p><p>When data comes back from the server, it provides a blueprint for how the store’s data should change in response to the mutation. The blueprint guides the store in figuring out how to change fields or delete data.</p><p>This set of blueprints is handed off to the mutation system.</p><h4>The mutation system</h4><p>The mutation system is like a contractor carrying out and directing the work on that set of blueprints.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*r23vgCYGYzwxRwQBwPTpiQ.png" /></figure><p>It takes the blueprint for the fat query and compares it to the graph of data that the app is currently using, called the tracked query. It figures out which data needs to be refreshed. If a property is in both graphs, it gets added to the mutation request.</p><p><em>Note: The mutation defines this fat query, not the component. This means even if a seemingly unrelated component has made a change, if it impacts another component’s data, all of the changed data will still be fetched from the server. This is great because you get consistency without coupling components together.</em></p><p>If the mutation has a blueprint for an optimistic update, it carries that out.</p><h3>How the store and mutation system team up</h3><p>Just as the store works with the query system for fetching data, it works with the mutation system for changing data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*bA2CJCYiC5VIRcg4vuYOjA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*GPlsJFRd7xhtf4HeWKoSqA.png" /></figure><p>1. The UI passes a mutation object to the store.</p><p>2. The store passes the mutation to the mutation system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*j91QK_rfdtW6s7gWrSfaVg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*AbbOvM9NnblD3m4FfPBcNg.png" /></figure><p>3. The mutation system figures out what the optimistic update should be. It tells the store to update the cache with that data.</p><p>4. The store writes the data and sets up a broadcast to fire later. That broadcast will let the UI know that there is new data to show.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*kuPB05Cwgk6nF5s-HuZusQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*jzO65_YACRDhVex2krNF5w.png" /></figure><p>5. The mutation system compares the fat and tracked queries to figure out the smallest bit of data that the server needs to send down. It sends the request, which includes the change to make and the query.</p><p>6. The broadcast that the store set up in step 4 goes out. The UI requests the data that the optimistic update changed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Z9Kgg2ayY_aNLIaPMEc1uQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*F6RmjaDIxUe2GiyqmKeckg.png" /></figure><p>7. The mutation system receives the payload. It passes it to the store, which updates the cache. Then it queues up another broadcast to the UI.</p><p>8. The UI gets the new data from the store.</p><p>So that’s how I think of mutations and data syncing in Relay. Hope it helps!</p><blockquote>Did this help? If it did, a click on the ♥ is much appreciated… it helps other people find it, too!</blockquote><h3><strong><em>Coming up next…</em></strong></h3><p>See how <a href="https://code-cartoons.com/a-cartoon-intro-to-facebook-s-relay-part-4-aef7d819a8ed#.d24jmwxgd">it all fits together in part 4</a>.</p><figure><a href="https://leanpub.com/codecartoons-react"><img alt="" src="https://cdn-images-1.medium.com/max/600/1*b4pDY7WpzfoGJ2IeRnSiYQ.png" /></a></figure><figure><a href="http://tinyletter.com/codecartoons"><img alt="" src="https://cdn-images-1.medium.com/max/250/1*Vhx6UMeHXRPAEOGaPq8vQA.png" /></a></figure><figure><a href="https://twitter.com/codecartoons"><img alt="" src="https://cdn-images-1.medium.com/max/250/1*_oQtFJQYeeOkz4T81Sg4dA.png" /></a></figure><h3>Resources</h3><ol><li><a href="http://graphql.org/">GraphQL docs</a></li><li><a href="https://facebook.github.io/relay/docs/getting-started.html">Relay docs</a></li><li><a href="https://youtu.be/9sc8Pyc51uU">Talk at React.js Conf January 2015</a></li><li><a href="https://www.youtube.com/watch?v=_9RgHXqH8J0">Exploring GraphQL</a></li><li><a href="http://softwareengineeringdaily.com/2015/09/19/graphql-and-relay-with-nick-schrock/">GraphQL and Relay with Nick Schrock</a></li><li><a href="https://blog.jacobwgillespie.com/from-rest-to-graphql-b4e95e94c26b">From REST to GraphQL</a></li><li><a href="https://devchat.tv/adventures-in-angular/043-aia-falcor-with-jafar-husain">Falcor with Jafar Husain</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d8fcf8db670" width="1" height="1" alt=""><hr><p><a href="https://medium.com/code-cartoons/a-cartoon-intro-to-facebook-s-relay-part-3-9d8fcf8db670">A cartoon guide to Facebook’s Relay, part 3</a> was originally published in <a href="https://medium.com/code-cartoons">Code Cartoons</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A cartoon guide to Facebook’s Relay, part 2]]></title>
            <link>https://medium.com/code-cartoons/a-cartoon-intro-to-facebook-s-relay-part-2-d4a2435aee59?source=rss-d3391efe481a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4a2435aee59</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Lin Clark]]></dc:creator>
            <pubDate>Fri, 22 Jan 2016 13:57:03 GMT</pubDate>
            <atom:updated>2016-01-27T00:43:13.490Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kRnCI6fxor6U2KNJrtEJZA.gif" /></figure><p>GraphQL gives you a way to say what part of a graph you need, as you saw in <a href="https://code-cartoons.com/a-cartoon-intro-to-facebook-s-relay-part-1-3ec1a127bca5">part 1</a>.</p><p>Relay makes the connection between the graph in the cloud and the graph that the user is interacting with on the page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*YvKb_HfICH_xnKQhNxyvVQ.png" /></figure><p>Relay can automate:</p><ol><li>downloading the bits of the graph that you need and caching them</li><li>making future requests for data smaller</li><li>figuring out which parts of the graph you really need right now, and which you can wait for</li></ol><p>It also automates syncing any changes to the graph back up to the server. We’ll cover this in <a href="https://code-cartoons.com/a-cartoon-intro-to-facebook-s-relay-part-3-9d8fcf8db670">part 3</a>.</p><h4>Downloading and caching</h4><p>The UI doesn’t talk to the server directly. Instead, it gets all of the data from the store, which has a local cache of the data.</p><p>When the page loads initially, the UI will ask the store to prime the cache. This will pull down the data from the server. Then the UI can do it’s first render.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dqCvF_8OnhWE29dgAwt77w.png" /><figcaption>(1) The request to the server (2) The response (3) UI renders the data</figcaption></figure><ol><li>First, the system needs to figure out what data to get from the server. It gathers all of the query fragments from the components that will be shown. Then, it stitches those together into a single graph. That graph query is requested from the server.</li><li>The server responds by filling in the part of the graph described by the query with the actual data. The data is added to the local cache.</li><li>The UI gets a notification that the data is ready and in the cache (more about this below). The UI asks the store for the data and renders it.</li></ol><h4>Making queries smaller</h4><p>Now we have data in the cache. Because of this, Relay can make future queries smaller.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FW-sIIMdJV8r1R9i63i_0Q.png" /><figcaption>(1) The initial query graph (2) The reduced query graph (3) The response and UI update</figcaption></figure><ol><li>The system figures out what parts of the query it already has and what parts it needs.</li><li>The part that is already cached is removed from the query. Then the reduced graph query is sent to the server.</li><li>The little bit of the graph that was missing is returned from the server. The store merges it into the local cache. The UI is notified that the data is in, and it asks the store for the data.</li></ol><h4>Deferring queries</h4><p>Sometimes, you have two kinds of data needs. Some data needs to be fetched immediately to render the page, and other data that can come in later.</p><p>For example, on a news article the article body needs to be rendered immediately. But comments, which aren’t really that important, can be rendered a few seconds later.</p><p>In theory, Relay makes it possible to split up the queries. When the required data comes in, the page will render. When the deferred data comes in, it will be added to the page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UtgxJ05bj92wPtqGLGpaCw.png" /><figcaption>(1) The split query graph (2) The first response and UI render (3) The second response and UI update</figcaption></figure><ol><li>The query graph is split up based on whether the properties are deferred. The deferred query is marked as dependent on the required query.</li><li>The server responds with the required data. The UI renders the page with that data.</li><li>The server responds with the deferred data. The UI updates the page with the data.</li></ol><p><em>Note: While Relay itself can handle deferred queries, there is a piece of the puzzle missing. Facebook’s GraphQL server can handle dependencies between queries, but for simplicity’s sake they didn’t add it to the GraphQL spec. They do plan to make it possible though, and you can </em><a href="https://github.com/facebook/relay/issues/288"><em>follow the issue</em></a><em>.</em></p><p>To do these things, Relay introduces a new character — the query system.</p><h3>Introducing the query system</h3><p>The query system is in charge of figuring out what data to fetch. It works together with the store to figure out the smallest queries that it can send.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*0YTeXXUux1iTQI7o_80v4w.png" /></figure><p>I think of the query system as a bike messenger who’s obsessed with efficiency. Before sending a query, it checks what data is in the store. It won’t ask the server for data the store already has.</p><p>It will even go above and beyond to make the query smaller. It checks what data is supposed to come in from pending requests. Instead of sending a concurrent request for the same data, it will just clip away parts that it expects to come in from the pending requests.</p><h3>How the store and query system team up</h3><p>The query system is just a small part of Relay. I’ll cover the rest of the characters later. But I think it’s helpful to get a detailed view of how the query system works with the store to automate data fetching, and how the two talk with the server and the UI.</p><p><em>Note: Everything in this cartoon is automatically handled by Relay. So you don’t technically need to know how this works. But it’s more fun when you do!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*LBbmRc3jfKMptW5OKQQn0A.png" /></figure><p>Here’s an example of the interaction between these two.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*uJxu9d8HE5CZtXMoT-fL3g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*MrqYtlCNvnUkJcDi0ZwwAQ.png" /></figure><p>1. The UI asks the store to fill up the cache. Specifically, it asks for the data that is needed for the first render.</p><p>2. The store delegates this to the query system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*3aGYCGJ16v0QmLn9puZpMA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*7GvV5kBPJBx3FwCOV8-Z0w.png" /></figure><p>3. The query system tries to make the query as small as possible.</p><p>4. The query system sends the query off. It adds it to the list of requests that are pending.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*h9wg74wjwD9F-IRlzQ3thA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*OrOy2BrTlS3ydwUkih7f-A.png" /></figure><p>5. In the meantime, the query system wants to let the UI know what’s going on.</p><p>It sends a ready state message to the UI (it does this with a callback that the UI passed to the store, and the store passed to it). In the ready state message, the ready property is set to false since the data hasn’t come in yet.</p><p>6. When the query results come back, the query system sends them to the store. It also removes the request from the list of pending requests. The store adds the results to the local cache.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*-jKEqrO71n9giuypZodhzg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*ph4k0Qh7mSm286wzLv7QVw.png" /></figure><p>7. The query system lets the UI know that it can get the data from the store.</p><p>8. The UI asks the store for the data. The store gives it the data and also sets up some observers. These will be used to target updates to specific components when new data comes in.</p><p>So that’s how I think of data fetching in Relay. Hope it helps!</p><blockquote>Did this help? If it did, a click on the ♥ is much appreciated… it helps other people find it, too!</blockquote><h3>Coming up next</h3><p><a href="https://code-cartoons.com/a-cartoon-intro-to-facebook-s-relay-part-3-9d8fcf8db670#.pqb0zavx0">Syncing changes back up to the server</a> with Relay.</p><figure><a href="https://leanpub.com/codecartoons-react"><img alt="" src="https://cdn-images-1.medium.com/max/600/1*b4pDY7WpzfoGJ2IeRnSiYQ.png" /></a></figure><figure><a href="http://tinyletter.com/codecartoons"><img alt="" src="https://cdn-images-1.medium.com/max/250/1*Vhx6UMeHXRPAEOGaPq8vQA.png" /></a></figure><figure><a href="https://twitter.com/codecartoons"><img alt="" src="https://cdn-images-1.medium.com/max/250/1*_oQtFJQYeeOkz4T81Sg4dA.png" /></a></figure><h3>Resources</h3><ol><li><a href="http://graphql.org/">GraphQL docs</a></li><li><a href="https://facebook.github.io/relay/docs/getting-started.html">Relay docs</a></li><li><a href="https://youtu.be/9sc8Pyc51uU">Talk at React.js Conf January 2015</a></li><li><a href="https://www.youtube.com/watch?v=_9RgHXqH8J0">Exploring GraphQL</a></li><li><a href="http://softwareengineeringdaily.com/2015/09/19/graphql-and-relay-with-nick-schrock/">GraphQL and Relay with Nick Schrock</a></li><li><a href="https://blog.jacobwgillespie.com/from-rest-to-graphql-b4e95e94c26b">From REST to GraphQL</a></li><li><a href="https://devchat.tv/adventures-in-angular/043-aia-falcor-with-jafar-husain">Falcor with Jafar Husain</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4a2435aee59" width="1" height="1" alt=""><hr><p><a href="https://medium.com/code-cartoons/a-cartoon-intro-to-facebook-s-relay-part-2-d4a2435aee59">A cartoon guide to Facebook’s Relay, part 2</a> was originally published in <a href="https://medium.com/code-cartoons">Code Cartoons</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A cartoon guide to Facebook’s Relay, part 1]]></title>
            <link>https://medium.com/code-cartoons/a-cartoon-intro-to-facebook-s-relay-part-1-3ec1a127bca5?source=rss-d3391efe481a------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ec1a127bca5</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Lin Clark]]></dc:creator>
            <pubDate>Wed, 20 Jan 2016 14:06:06 GMT</pubDate>
            <atom:updated>2016-01-27T00:43:38.807Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7ogNpAoyFsNKsdI5OePz3g.gif" /></figure><p>The last two cartoons covered <a href="https://code-cartoons.com/a-cartoon-guide-to-flux-6157355ab207">Flux</a> and <a href="https://code-cartoons.com/a-cartoon-intro-to-redux-3afb775501a6">Redux</a>. Those are data handling patterns to keep your UI in sync. When a user interaction happens, they update the state and trigger rerendering.</p><p>But where’s the cloud? How do you get the data that a component needs from a server, and then update the server when the user makes changes?</p><p>The Flux docs don’t tell you were to put this. Even at Facebook, different teams add it in <a href="https://www.youtube.com/watch?v=LTj4O7WJJ98">different parts</a> of the app. Redux gives you a <a href="http://rackt.org/redux/docs/advanced/AsyncActions.html">single place</a> to do it (middleware), but it still requires effort to wire it up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*NHDDxO6XCae_E_MIYTwTTQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*082Zf3VMDP-sw1_2AVp-Uw.png" /><figcaption>Where’s the cloud? There’s no set spot in Flux (left). Redux (right) uses middleware.</figcaption></figure><p>Relay takes care of this problem. It makes it easy to fetch data from the server as part of your data flow. In order to do this, Relay needs to know what data each component needs from the server. This is where GraphQL comes in.</p><p>So let’s look at GraphQL. But first…</p><h3>What is a graph?</h3><p>You might think of a graph as the same thing as a chart, or the graphs you made on a graphing calculator. That’s not the kind of graph we’re talking about.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*PN4C-ibbH6VYgB2KGqZ4AQ.png" /></figure><p>The kind of graph we’re talking about is a group of things that are connected to each other by relationships. These things and relationships have special names in graph theory. The things are called nodes and the relationships between them are called edges.</p><p>If that sounds unfamiliar, just think of a property chain. For example, user.friend[0].attending[0]. That’ another way of thinking about the same graph.</p><p>If you look at an app like Facebook, a graph is the most natural way to think about the data. There are lots of things, and lots of relationships between those things.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Z2E7qE6WjVxticHSfjii4g.png" /></figure><p>When you pull up a page on Facebook, it’s showing you a particular view of that graph. And each component on the page shows you a small slice of the graph.</p><p>So how do you make the connection between a component and the small section of the graph that it displays?</p><p>This is what GraphQL does. It makes it possible to indicate the small section of the graph that you want. This small section is called a fragment. The fragments combine to create a larger query.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*LNgLStpmUDAqW2m5CvNgBQ.png" /></figure><p>Relay piggybacks on this capability—being able to combine multiple fragments into a larger query — to solve a problem.</p><h3>The problem</h3><p>So what is the problem that Relay solves using GraphQL?</p><p>When you build React components, it’s easy to reuse them across different parts of your site. This is one of the main benefits of React. It’s called composability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*bORAT4s4OVuvNcX8Qk6sew.png" /></figure><p>If your component needs to use data from the server, though, it gets harder to just drop a component in place. The server needs to know what properties the component needs. In many apps, this will be hard-coded on the server. There will be a URL (called an endpoint) that passes down data for that particular view. The endpoint code will know exactly what properties its view needs.</p><p>The problem here is that whenever you add (or remove) properties from the component, you have to change the server code too. This is called coupling; when you change one, you have to change the other, too.</p><p>Because you have to manually keep these two in sync, it makes bugs and obsolete code more likely.</p><ul><li>Bugs come from underfetching data. You don’t pull down the properties that you need for a component because you forgot to add them to the server.</li><li>Obsolete code results in overfetching data. For example, let’s say you remove a component from the tree. Do you delete its properties from the server response? How can you be sure another component doesn’t use that endpoint and need those properties? Instead, it’s better to just keep them in the response… but then you have a lot of cruft lying around.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*W-Gpb1voGJ8Km2tg19xgzw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*WkbMDnWMWwg1-eqLNMpr0w.png" /></figure><h3>The solution: declarative data fetching</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*RkASoUKbg9vRrn6HGjKVEg.png" /></figure><p>With GraphQL, you don’t hard-code the server with the list of properties that your view needs. Instead, the component provides a list of what it needs to the server.</p><p>This list is combined with the lists from other components. The structure of the combined list is a tree, just like the component tree. It gets handed off to the endpoint. There’s only one endpoint and it handles all requests.</p><p>The nice thing about this is that it localizes changes. When you need to add or remove a property, you only need to change the component… not the server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*S9q6g-juaMU8P6Jzr1M1Mw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*2eicaDu-YdFSUMk8puENlA.png" /></figure><h3>What GraphQL looks like</h3><p>To make this work, each component needs to provide the list of properties that it needs from the server. This is the query fragment. Relay will figure out which components are going to render and will get the query fragments for them. It will compile these into a single query — a consolidated list of properties that it needs from the server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Q06oM_W7ut-FTPEw_WynrQ.png" /></figure><p>This turns into a query like this:</p><pre>query {<br>  user(id: 5) {<br>    friends(first: 3) {<br>      picture<br>      name<br>      location<br>    }<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*vy212Nf7CtOCgodDJ9sgNQ.png" /></figure><p>This consolidated query is kind of like a questionnaire. The client has laid out all of the questions it wants the server to answer, and the server just needs to fill in the blanks.</p><p>One important thing to note: GraphQL doesn’t actually store your data. It just gives you a language to ask for data.</p><p>If your database is the public library, then GraphQL would be the librarian. It just listens to your request and figures out what you want. Then it goes around to the different bookshelves and finds the data that you asked for. The bookshelves in this analogy are the tables of your database, or whatever you are holding your data in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*fRpthdNa2ON6_c6UEmNGIw.png" /></figure><p>This means you can use GraphQL on top of all sorts of different backends; an existing MySQL database, a NoSQL database like MongoDB, or even on top of regular text files.</p><p>For each property in the query, the server will have a <em>resolve()</em> function. This is where GraphQL figures out the value and fills in that question on the questionnaire, computing a value or querying a database.</p><p>There’s a lot more to GraphQL, but this is enough to get started with Relay. Let me know <a href="http://twitter.com/codecartoons">on Twitter</a> if you’d like to see a GraphQL deep dive in the future.</p><h3>Coming up next…</h3><p>There’s more work to do than just splitting up the query. That’s where Relay comes in. I’ll cover that in <a href="https://code-cartoons.com/a-cartoon-intro-to-facebook-s-relay-part-2-d4a2435aee59">part 2</a>.</p><blockquote>Did this help? If it did, a click on the ♥ is much appreciated… it helps other people find it, too!</blockquote><figure><a href="https://leanpub.com/codecartoons-react"><img alt="" src="https://cdn-images-1.medium.com/max/600/1*b4pDY7WpzfoGJ2IeRnSiYQ.png" /></a></figure><figure><a href="http://tinyletter.com/codecartoons"><img alt="" src="https://cdn-images-1.medium.com/max/250/1*Vhx6UMeHXRPAEOGaPq8vQA.png" /></a></figure><figure><a href="https://twitter.com/codecartoons"><img alt="" src="https://cdn-images-1.medium.com/max/250/1*_oQtFJQYeeOkz4T81Sg4dA.png" /></a></figure><h3>Resources</h3><ol><li><a href="http://graphql.org/">GraphQL docs</a></li><li><a href="https://facebook.github.io/relay/docs/getting-started.html">Relay docs</a></li><li><a href="https://youtu.be/9sc8Pyc51uU">Talk at React.js Conf January 2015</a></li><li><a href="https://www.youtube.com/watch?v=_9RgHXqH8J0">Exploring GraphQL</a></li><li><a href="http://softwareengineeringdaily.com/2015/09/19/graphql-and-relay-with-nick-schrock/">GraphQL and Relay with Nick Schrock</a></li><li><a href="https://blog.jacobwgillespie.com/from-rest-to-graphql-b4e95e94c26b">From REST to GraphQL</a></li><li><a href="https://devchat.tv/adventures-in-angular/043-aia-falcor-with-jafar-husain">Falcor with Jafar Husain</a></li></ol><p><em>Thank you to all of my reviewers on this series: </em><a href="https://twitter.com/kentcdodds"><em>Kent C. Dodds</em></a><em>, </em><a href="https://twitter.com/leeb"><em>Lee Byron</em></a><em>, </em><a href="https://twitter.com/steveluscher"><em>Steven Luscher</em></a><em>, </em><a href="https://twitter.com/yungsters"><em>Tim Yung</em></a><em>, and </em><a href="https://twitter.com/thefubhy"><em>Sebastian Siemssen</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ec1a127bca5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/code-cartoons/a-cartoon-intro-to-facebook-s-relay-part-1-3ec1a127bca5">A cartoon guide to Facebook’s Relay, part 1</a> was originally published in <a href="https://medium.com/code-cartoons">Code Cartoons</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A cartoon intro to Redux]]></title>
            <link>https://medium.com/code-cartoons/a-cartoon-intro-to-redux-3afb775501a6?source=rss-d3391efe481a------2</link>
            <guid isPermaLink="false">https://medium.com/p/3afb775501a6</guid>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Lin Clark]]></dc:creator>
            <pubDate>Wed, 21 Oct 2015 12:13:56 GMT</pubDate>
            <atom:updated>2015-10-26T13:55:32.124Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dODKUGyGkF8qeGLrXKWkiA.png" /><figcaption>Other languages: <a href="http://bestalign.github.io/2015/10/26/cartoon-intro-to-redux/">한국어</a>, <a href="https://medium.com/russian/a-cartoon-intro-to-redux-e2108896f7e6#.wxgkcsq14">Русский</a>.</figcaption></figure><p>One thing that causes even more confusion than Flux is the difference between Flux and Redux, a pattern that was inspired by Flux. In this article I’ll explain the differences between the two.</p><p>If you haven’t read the <a href="https://code-cartoons.com/a-cartoon-guide-to-flux-6157355ab207">last article about Flux</a>, you should do that first.</p><h3>Why change Flux?</h3><p>Redux solves the same problems as Flux, plus some.</p><p>Just like Flux, it makes state changes in apps more predictable. If you want to change state, you have to fire off an action. There’s no way to change the state directly because the thing holding the state (the store) only has a getter, not setters. These basics of Flux and Redux are pretty similar.</p><p>So why a different pattern? Redux creator Dan Abramov saw an opportunity to improve on Flux. He wanted better developer tools. He saw that if you moved a couple of things around, you could make better developer tools possible, but still have the same predictability that Flux gives you.</p><p>He wanted hot reloading and time travel debugging (there’s <a href="https://medium.com/@linclark/hot-reloading-and-time-travel-debugging-what-are-they-3c8ed2812f35">another cartoon to explain these</a>). But there were some problems which made developer tooling hard to do with Flux.</p><h4>Problem 1: The code for stores can’t be reloaded without wiping out the state</h4><p>In Flux, the store contains two things:</p><ol><li>The state change logic</li><li>The current state itself</li></ol><p>Having these two on the same object is a problem for hot reloading. When you reload the store object to see the effect that the new state change logic has, you lose the state that the store is holding on to. Plus, you mess up the event subscriptions that tie the store to the rest of the system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*L66K9uCQjjHmpAwT-a9C5Q.png" /></figure><p><strong>Solution<br></strong>Separate these two functions. Have one object that holds on to the state. This object doesn’t get reloaded. Have another object that contains all of the state change logic. This object can be reloaded because it doesn’t have to worry about holding on to any state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*nBsGCWmJTR-Zj7aXeIE8yg.png" /></figure><h4>Problem 2: The state is being rewritten with every action</h4><p>In time travel debugging, you keep track of each version of a state object. That way, you can go back to an earlier state.</p><p>Each time the state is changed, you need to add the old state to an array of previous state objects. But because of the way JavaScript works, simply adding the variable to the array won’t work. This doesn’t create a snapshot of the object, it just creates a new pointer to the same object.</p><p>To make it work, each version needs to be an entirely separate object so that you aren’t accidentally changing past versions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*4zODv5vgvKsi6Ts7TihsoA.png" /></figure><p><strong>Solution</strong><br>When an action comes in to the store, don’t handle it by changing the state. Instead, copy the state and make changes to the copy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*wLRhZ0wtI0duLsigdxL1CA.png" /></figure><h4>Problem 3: There aren’t good places for third-party plugins to jump in</h4><p>When you’re making developer tools, you need to be able to write them generically. A user should be able to just drop the tool in without having to custom fit their own code around it.</p><p>For this to work, you need extension points… places where the code expects to have things added to it.</p><p>An example is logging. Let’s say you want to console.log() every action as it comes in, and then console.log() the state that results from it. In Flux, you’d have to subscribe to the dispatcher’s updates and to updates from each store. But that’s custom code, not something a third-party module can easily do.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*MG736zGtLMBbSkhwu4D3cA.png" /></figure><p><strong>Solution</strong><br>Make it easy to wrap parts of the system in other objects. These other objects add their bit of functionality on top of the original. You can see these kinds of extension points in things like “enhancers” or “higher order” objects, as well as middleware.</p><p>In addition, use a tree to structure the state change logic. This makes it so the store only emits one event to notify the views that the state has changed. This event comes after the whole state tree has been processed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*5JaZSc3Jsn9PJY7daEDVDA.png" /></figure><p><em>Note: With these problems and solutions, I‘m focusing on the developer tooling use case. These changes help in other use cases, too. On top of that, there are other differences between Redux and Flux. For example, Redux also reduces boilerplate and it makes it easier to reuse logic in the store. Here’s a list of some other </em><a href="http://stackoverflow.com/a/32920459"><em>upsides to Redux</em></a><em>.</em></p><p>So let’s see how Redux makes these things possible.</p><h3>The new cast of characters</h3><p>The cast of characters changes a little bit from Flux to Redux.</p><h4>Action creators</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*Uljrrh4Z7UiUwk8AjUO9PA.png" /></figure><p>Redux keeps the action creator from Flux. Whenever you want to change the state of the application, you shoot off an action. That’s the only way that the state should be changed.</p><p>As I said in the <a href="https://code-cartoons.com/a-cartoon-guide-to-flux-6157355ab207">article on Flux</a>, I think of the action creator as a telegraph operator. You go to the action creator knowing basically what message you want to send, and then the action creator formats that in a way that the rest of the system can understand.</p><p>Unlike Flux, action creators in Redux do not send the action to the dispatcher. Instead, they return a formatted action object.</p><h4>The store</h4><p>I described stores in Flux as over-controlling bureaucrats. All state changes must be made personally by a store and have to go through the action pipeline, instead of being requested directly. The store in Redux is still controlling and bureaucratic, but it’s a little bit different.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*Gztc7THzxzOgJmGvJ95IQA.png" /></figure><p>In Flux, you can have multiple stores. Each store has its own little fiefdom, and it is in total control. It holds on to its little slice of state, and has all the logic for changing that little slice of state.</p><p>The Redux store tends to delegate more. And it has to. In Redux, there is only one store… so if it did everything itself, it would be taking on too much work.</p><p>Instead, it takes care of holding on to the whole state tree. It then delegates the work of figuring out what state changes need to happen. The reducers, headed up by the root reducer, take on this task.</p><p>You might have noticed there’s no dispatcher. That’s because, in a bit of a power grab, the store has also taken over dispatching.</p><h4>The reducers</h4><p>When the store needs to know how an action changes the state, it asks the reducers. The root reducer takes charge and slices the state up based on the state object’s keys. It passes each slice of state to the reducer that knows how to handle it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*Vocy_6Gl9PbFlCIJsE9r3A.png" /></figure><p>I think of the reducers as a department of white-collar workers who are a little overzealous about photocopying. They don’t want to mess anything up, so they don’t change the state that has been passed in to them. Instead, they make a copy and make all their changes on the copy.</p><p>This is one of the key ideas of Redux. The state object isn’t manipulated directly. Instead, each slice is copied and then all of the slices are combined into a new state object.</p><p>The reducers pass their copies back to the root reducer, which pastes the copies together to form the updated state object. Then the root reducer sends the new state object back to the store, and the store makes it the new official state.</p><p>If you have a small application, you might only have one reducer making a copy of the whole state object and making its changes. Or if you have a large application, you might have a whole tree of reducers. This is another difference between Flux and Redux. In Flux, the stores aren’t necessarily connected to each other and they have a flat structure. In Redux, the reducers are in a heirarchy. This hierarchy can have as many levels as needed, just like the component hierarchy.</p><h4>The views: smart and dumb components</h4><p>Flux has controller views and regular views. The controller views act as middle managers, managing the communication between the store and their child views.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*TgCkFcjlD9SxSrMvVX3DrA.png" /></figure><p>In Redux, there’s a similar concept: smart and dumb components. The smart components are the managers. They follow a few more rules than the controller views, though:</p><ul><li>Smart components are in charge of the actions. If a dumb component underneath them needs to trigger an action, the smart component passes a function in via the props. The dumb component can then just treat that as a callback.</li><li>Smart components do not have their own CSS styles.</li><li>Smart components rarely emit DOM of their own. Instead, they arrange dumb components, which handle laying out DOM elements.</li></ul><p>Dumb components don’t depend on action files directly, since all actions are passed in via props. This means that the dumb component can be reused in a different app that has different logic. They also contain the styles that they need to look reasonably good (though you can allow for custom styling — just accept a style prop and merge it in to the default styles).</p><h4>The view layer binding</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*D1RcVrMV2rp6AH9hk5xZ8g.png" /></figure><p>To connect the store to the views, Redux needs a little help. It needs something to bind the two together. This is called the view layer binding. If you’re using React, this is react-redux.</p><p>The view layer binding is kind of like the IT department for the view tree. It makes sure that all of the components can connect to the store. It also takes care of a lot of technical details so that the rest of the hierarchy doesn’t have to understand them.</p><p>The view layer binding introduces three concepts:</p><ol><li>The Provider component: This is wrapped around the component tree. It makes it easy for the root component’s children to hook up to the store using connect().</li><li>connect(): This is a function provided by react-redux. If a component wants to get state updates, it wraps itself using connect(). Then the connect function will set up all the wiring for it, using the selector.</li><li>selector: This is a function that you write. It specifies what parts of the state a component needs as properties.</li></ol><h4>The root component</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*JXPeiNP-it60-QYKb-p2eQ.png" /></figure><p>All React applications have root components. This is just the component at the top level of the component hierarchy. But in Redux applications, this component takes on more responsibility.</p><p>The role it plays is kind of like a C-level executive. It puts all of the teams in place to tackle the work. It creates the store, telling it what reducer to use, and brings together the view layer binding and the views.</p><p>The root component is pretty hands-off after it initializes the app, though. It doesn’t get caught up in the day-to-day concerns of triggering rerenders. It leaves that to the components below it, assisted by the view layer binding.</p><h3>How they all work together</h3><p>Let’s see how these parts work together to create a functioning app.</p><h4>The setup</h4><p>The different parts of the app need to be wired up together. This happens in setup.</p><p>1. <strong>Get the store ready.</strong> The root component creates the store, telling it what root reducer to use, using createStore(). This root reducer already has a team of reducers which report to it. It assembled that team of reducers using combineReducers().</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*8_fU31-jNQnQ0dp-wplm5w.png" /></figure><p>2. <strong>Set up the communication between the store and the components. </strong>The root component wraps its subcomponents with the provider component and makes the connection between the store and the provider.</p><p>The Provider creates what’s basically a network to update the components. The smart components connect to network using connect(). This ensures they’ll get state updates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*NYMutQLW8TcEgbO8VNeqHA.png" /></figure><p>3. <strong>Prepare the action callbacks.</strong> To make it easier for dumb components to work with actions, the smart components can setup action callbacks by using bindActionCreators(). This way, they can just pass down a callback to the dumb component. The action will be automatically dispatched after it is formatted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*aVoD3gGddKUy3VCxwylthQ.png" /></figure><h4>The data flow</h4><p>Now that the application is set up, the user can start interacting with it. Let’s trigger an action to see the data flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*GNDs7SY53lEhp7mX8V25lw.png" /></figure><p>1. The view requests an action. The action creator formats it and returns it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*p4EkWE_8upZ97Z0IapKDcQ.png" /></figure><p>2. The action is either dispatched automatically (if bindActionCreators() was used in setup), or the view dispatches the action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*zmFp3bmDq7b6Bvlo8Ineag.png" /></figure><p>3. The store receives the action. It sends the current state tree and the action to the root reducer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*zrsSoAAyf4pqTMHiA6P8Ww.png" /></figure><p>4. The root reducer cuts apart the state tree into slices. Then it passes each slice to the subreducer that knows how to deal with it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*-S_dYe6BoQBgwSRpF7Hriw.png" /></figure><p>5. The subreducer copies the slice and makes changes to the copy. It returns the copy of the slice to the root reducer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*_R-rGNfKr2Xu2FlXNZNPJg.png" /></figure><p>6. Once all of the subreducers have returned their slice copies, the root reducer pastes all of them together to form the whole updated state tree, which it returns to the store. The store replaces the old state tree with the new one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*bUMekI8QlEfFxSBCuVuIkw.png" /></figure><p>7. The store tells the view layer binding that there’s new state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*x6vBvUlFJktJqty56jr0QQ.png" /></figure><p>8. The view layer binding asks the store to send over the new state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*qGatznV4QujuxGe49YfX5A.png" /></figure><p>9. The view layer binding triggers a rerender.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*Je2mow8mjYLngXreGGlIEg.png" /></figure><p>So that’s how I think of Redux and its differences from Flux. Hope it helps!</p><h3>Coming up next</h3><p>I’m making a list of topics. If you have any suggestions, or there are any parts of the React ecosystem that you find confusing and you’d like to see explained, let me know on <a href="https://twitter.com/codecartoons">Twitter</a>.</p><figure><a href="https://leanpub.com/codecartoons-react"><img alt="" src="https://cdn-images-1.medium.com/max/600/1*b4pDY7WpzfoGJ2IeRnSiYQ.png" /></a></figure><figure><a href="https://tinyletter.com/codecartoons"><img alt="" src="https://cdn-images-1.medium.com/max/250/1*Vhx6UMeHXRPAEOGaPq8vQA.png" /></a></figure><figure><a href="https://twitter.com/codecartoons"><img alt="" src="https://cdn-images-1.medium.com/max/250/1*_oQtFJQYeeOkz4T81Sg4dA.png" /></a></figure><h3>Resources</h3><ul><li><a href="http://rackt.org/redux/index.html">Redux docs</a></li><li><a href="https://www.youtube.com/watch?v=xsSnOQynTHs">Dan Abramov’s React Europe talk</a></li><li><a href="https://medium.com/@dan_abramov/the-evolution-of-flux-frameworks-6c16ad26bb31">The Evolution of Flux Frameworks</a></li><li><a href="https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0">Smart and Dumb Components</a></li><li><a href="http://stackoverflow.com/a/32920459">The upsides of using Redux</a></li><li><a href="http://stackoverflow.com/a/32916602">The downsides of using Redux</a></li><li><a href="https://devchat.tv/js-jabber/181-jsj-the-evolution-of-flux-libraries-with-andrew-clark-and-dan-abramov">JS Jabber: The Evolution of Flux Libraries with Andrew Clark and Dan Abramov</a></li></ul><p><em>Thank you to the amazing </em><a href="http://twitter.com/dan_abramov"><em>Dan Abramov</em></a><em>, </em><a href="https://twitter.com/kentcdodds"><em>Kent C. Dodds</em></a><em> and </em><a href="https://twitter.com/mzabriskie"><em>Matt Zabriskie</em></a><em> for their feedback.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3afb775501a6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/code-cartoons/a-cartoon-intro-to-redux-3afb775501a6">A cartoon intro to Redux</a> was originally published in <a href="https://medium.com/code-cartoons">Code Cartoons</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hot reloading and time travel debugging: what are they?]]></title>
            <link>https://medium.com/code-cartoons/hot-reloading-and-time-travel-debugging-what-are-they-3c8ed2812f35?source=rss-d3391efe481a------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c8ed2812f35</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[devtools]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Lin Clark]]></dc:creator>
            <pubDate>Wed, 21 Oct 2015 12:11:30 GMT</pubDate>
            <atom:updated>2015-10-27T12:08:01.490Z</atom:updated>
            <content:encoded><![CDATA[<p>Two of the features that get people excited about Redux are hot reloading and time travel debugging. But what are they?</p><h4>Hot reloading</h4><p>When you’re developing an app, you’re usually making one small change after another. The faster you can see the effects of the small changes (and recover from the small mistakes that you make), the faster you will develop.</p><p>The neat thing about hot reloading is that your app’s state isn’t reset after every change. Let’s say you’re testing a particular screen. You’ve added a few todo items and crossed a few off. But now you realize you need to change some UI text. For example, you need to change the placeholder from “New toto” to “New todo”.</p><p>Without hot reloading, you’d have to:</p><ul><li>Make the change in your code</li><li>Refresh the page in your browser</li><li>Re-add the data and push all of the same buttons</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*6xdA93PT8l61i0ptXVWpOw.png" /><figcaption>Without hot reloading, the todos go away when you reload the page.</figcaption></figure><p>With hot reloading, you don’t have to re-add the data because you don’t lose the state. Your list of todos will still be there. This makes debugging a lot faster.</p><p>Even if a React app doesn’t use Redux for its data, you can do hot reloading. You’re just limited in what you can hot reload. Views and action creators can be hot reloaded, but the store cannot. This is because the store has two roles: changing state based on actions and holding on to state. If the state change code is reloaded, you lose the state that the store is currently holding on to.</p><p>That’s what Redux gives you here: the ability to hot reload the state logic. And it does that by separating those two roles. In Redux, the store holds on to the state, but the state change logic is done by a different object, the reducer. This means you can hot reload your state change logic (reducers) without losing the state the store is holding on to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*Z5Na_SX0yHZYMSTpXIrxEQ.png" /><figcaption>With Redux’s hot reloading, you don’t lose the application state.</figcaption></figure><h4>Time travel debugging</h4><p>Hot reloading lets you keep your state even after code changed. With time travel debugging, you can go backwards to previous points in your state.</p><p>This makes it faster to test very specific parts of your interaction. For example, lets say you have a bug. It happens when you cross out a todo item and then add another. You would run through the full scenario once to set up your state. After that, you can just keep testing it by going backwards one step in your state and adding the second todo again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*E8b-Kwelt7YUMsS7GuSQYw.png" /><figcaption>Time travel debugging makes it easy to go back and forth to different points in the state history.</figcaption></figure><p>There are other exciting uses for this. You could record all of the actions of a QA tester. When the QA runs into a bug, they just need to package up the action and state history. You could even turn that into an automated test.</p><p>Time travel debugging is technically possible with Flux, but complicated. Redux makes it trivial.</p><h3>Coming up next</h3><p>See how Redux makes this all work:</p><p><a href="https://code-cartoons.com/a-cartoon-intro-to-redux-3afb775501a6#.w36q3cvk6">A cartoon intro to Redux - Code Cartoons</a></p><p>Other languages: <a href="http://bestalign.github.io/2015/10/27/redux-hot-reloading-and-time-travel-debugging/">한국어</a></p><figure><a href="https://leanpub.com/codecartoons-react"><img alt="" src="https://cdn-images-1.medium.com/max/600/1*b4pDY7WpzfoGJ2IeRnSiYQ.png" /></a></figure><figure><a href="https://tinyletter.com/codecartoons"><img alt="" src="https://cdn-images-1.medium.com/max/250/1*Vhx6UMeHXRPAEOGaPq8vQA.png" /></a></figure><figure><a href="https://twitter.com/codecartoons"><img alt="" src="https://cdn-images-1.medium.com/max/250/1*_oQtFJQYeeOkz4T81Sg4dA.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c8ed2812f35" width="1" height="1" alt=""><hr><p><a href="https://medium.com/code-cartoons/hot-reloading-and-time-travel-debugging-what-are-they-3c8ed2812f35">Hot reloading and time travel debugging: what are they?</a> was originally published in <a href="https://medium.com/code-cartoons">Code Cartoons</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A cartoon guide to Flux]]></title>
            <link>https://medium.com/code-cartoons/a-cartoon-guide-to-flux-6157355ab207?source=rss-d3391efe481a------2</link>
            <guid isPermaLink="false">https://medium.com/p/6157355ab207</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[flux]]></category>
            <dc:creator><![CDATA[Lin Clark]]></dc:creator>
            <pubDate>Tue, 29 Sep 2015 12:36:47 GMT</pubDate>
            <atom:updated>2016-01-09T22:55:56.983Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FPJJenCHGpL92Te39P19Ew.png" /><figcaption>Other languages: <a href="https://medium.com/@sotayamashita/%E6%BC%AB%E7%94%BB%E3%81%A7%E8%AA%AC%E6%98%8E%E3%81%99%E3%82%8B-flux-1a219e50232b#.24jpny5vi">日本語</a>, <a href="http://bestalign.github.io/2015/10/06/cartoon-guide-to-flux/">한국어</a>, <a href="https://medium.com/@sacret/%D1%80%D1%83%D0%BA%D0%BE%D0%B2%D0%BE%D0%B4%D1%81%D1%82%D0%B2%D0%BE-%D0%BF%D0%BE-flux-%D0%B2-%D0%BA%D0%B0%D1%80%D1%82%D0%B8%D0%BD%D0%BA%D0%B0%D1%85-df2b040224a3">Русский</a>.</figcaption></figure><p>Flux is both one of the most popular and one of the least understood topics in current web development. This guide is an attempt to explain it in a way everyone can understand.</p><h3>The problem</h3><p>First, I should explain the basic problem that Flux solves. Flux is a pattern for handling data in your application. Flux and React grew up together at Facebook. Many people use them together, though you can use them independently. They were developed to address a particular set of problems that Facebook was seeing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EfeNEshl8-uwZSuUw275Ag.png" /></figure><p>One really well known example of this set of problems was the notification bug. When you logged in to Facebook, you would see a notification over the messages icon. When you clicked on the messages icon, though, there would be no new message. The notification would go away. Then, a few minutes later after a few interactions with the site, the notification would come back. You&#39;d click on the messages icon again… still no new messages. It would just keep going back-and-forth in this cycle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4xc1FzIHWiyAvb1iAQKSqQ.png" /></figure><p>It wasn’t just a cycle for the user on the site. There was also a cycle going on for the team at Facebook. They would fix this bug and everything would be fine for a while and then the bug would be back. It would go back-and-forth between being resolved and being an issue again.</p><p>So Facebook was looking for a way to get out of this cycle. They didn’t want to just fix it once. They wanted to make the system predictable so they could ensure that this problem wouldn’t keep resurfacing.</p><h3>The underlying problem</h3><p>The underlying problem that they identified was the way that the data flowed through the application.</p><p><em>Note: this is what I’ve gleaned from simplified versions that they’ve shared in talks. I’m sure the actual architecture looked different.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*OcTeAqv8AU_z-O2HuucmeA.png" /><figcaption>Models pass data to the view layer.</figcaption></figure><p>They had models which held the data and would pass data to the view layer to render the data.</p><p>Because user interaction happened through the views, the views sometimes needed to update models based on user input. And sometimes models needed to update other models.</p><p>On top of that, sometimes these actions would trigger a cascade of other changes. I envision this as an edge-of-your-seat game of Pong — it’s hard to know where the ball is going to land (or fall off the screen).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*7myoHOaUyFEmPC-dj61CKw.png" /><figcaption>Views update models. Models update other models. This starts to look like a really edge-of-your-seat game of Pong.</figcaption></figure><p>Throw in the fact that these changes could be happening asynchronously. One change could trigger multiple other changes. I imagine this as throwing a whole bag of ping-pong balls into your Pong game, with them flying all over the place and crossing paths.</p><p>All in all, it makes for a hard to debug data flow.</p><h3>The solution: unidirectional data flow</h3><p>So Facebook decided to try a different kind of architecture, where the data flows in one direction — only one direction — and when you need to insert new data, the flow starts all over again at the beginning. They called their architecture Flux.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*lZM0yU9ExEMd7DggVxXkxA.png" /><figcaption>The diagram you’ll find in Facebook’s Flux docs. It is way cooler than it looks.</figcaption></figure><p>This is actually really cool… but you probably can’t tell it from the diagram above.</p><p>Once you understand Flux, this diagram is pretty clear. The problem is that if you’re coming to the documentation completely new to Flux, I don’t think that this diagram helps you understand it… and that’s what a diagram should do. It should give you a big picture understanding of a system before you dive in to really start figuring out how you do specific things.</p><p>What helped me understand Flux better wasn’t a diagram like this, but instead thinking of the system in terms of different characters working together as a team to achieve a goal. So I want to introduce you to the cast of characters that I have in my head.</p><h3>Meet the characters</h3><p>I’m just going to give a quick introduction to the characters before I explain how they all interact.</p><h4>The action creator</h4><p>The first character is the action creator. It’s in charge of creating actions, which is the path that all changes and interactions should go through. Whenever you want to change the state of the app or have the view render differently, you shoot off an action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*DATbW4s4Ls6UPieavtdB7w.png" /><figcaption>The action creator is like a telegraph operator. It formats your message for you.</figcaption></figure><p>I think of the action creator as a telegraph operator. You go to the action creator knowing basically what message you want to send, and then the action creator formats that in a way that the rest of the system can understand.</p><p>The action creator creates an action with a type and a payload. The type will be one of the types that you have defined as actions in your system (usually a list of constants). An example of an action would be something like MESSAGE_CREATE or MESSAGE_READ.</p><p>There’s a neat side effect to having a part of your system that knows all of the possible actions. A new developer can come on the project, open up the action creator files and see the entire API — all of the possible state changes — that your system provides.</p><p>Once it has created the action message, the action creator passes that action off to the dispatcher.</p><h4>The dispatcher</h4><p>The dispatcher is basically a big registry of callbacks. It’s kind of like a telephone operator at a phone switchboard. It keeps a list of all of the stores that it needs to send actions to. When an action comes in from the action creator, it will pass the action around to different stores.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*R5XHVGZfkPkmL7BcN5jMqg.png" /><figcaption>The dispatcher is like a switchboard operator. It knows all the callbacks for the different stores.</figcaption></figure><p>It does this in a synchronous way, which helps with that multi-ball Pong game effect that I was talking about earlier. And if you need to set up dependencies between stores so one gets updated before the other, you can have the dispatcher manage this for you with waitFor().</p><p>The Flux dispatcher is different from dispatchers in many other architectures. The action is sent to all of the registered stores regardless of what the action type is. This means the store doesn’t just subscribe to some actions. It hears about all actions and filters out what it cares about and doesn’t.</p><h4>The store</h4><p>Next is the store. The store holds on to all state in the application, and all of the state changing logic lives inside of the stores.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*17MbK8jz94ynP-NFfL0rfw.png" /><figcaption>The store is an over-controlling bureaucrat. All changes must go through it.</figcaption></figure><p>I think of the store as an over-controlling bureaucrat. All state changes must be made by it personally. And you can’t directly request that it change the state. There are no setters on the store. To request a state change, you must follow proper procedure… you must submit an action via the action creator/dispatcher pipeline.</p><p>As I mentioned above, if a store is registered with the dispatcher, all actions will be sent to it. Inside the store there’s usually a switch statement that looks at the action type to decide whether or not this store cares about this action. If the store does care about this action, it will figure out what change needs to be made based on this action and update the state.</p><p>Once the store has made its changes to the state, it will emit a change event. This will notify the controller view that the state has changed.</p><h4>The controller view and the view</h4><p>The views are in charge of taking the state and rendering it out for the user as well as accepting user input.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*MY5xNk_JeKvGsGdywYD4EA.png" /><figcaption>The controller view is like a middle manager who gets notifications from the store and passes the data onto the views under it. The view presents that data to the user.</figcaption></figure><p>The view is a presenter. It isn’t aware of anything in the application, it just knows the data that’s handed to it and how to format the data into output that people understand (via HTML).</p><p>The controller view is like a middle manager between the store and the view. The store tells it when the state has changed. It collects the new state and then passes the updated state along to all of the views under it.</p><h3>How they all work together</h3><p>So let’s take a look at how all of these characters work together.</p><h4>The setup</h4><p>First there’s the setup: application initialization which only happens once.</p><p>1. Stores let the dispatcher know that they want to be notified whenever an action comes in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*GHrusKRFhQ0Y6rrwjqI6QQ.png" /></figure><p>2. Then the controller views ask the stores for the latest state.</p><p>3. When the stores give the state to the controller views, they pass that state along to their child views to render.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*66hoDpUhczSXrgH2cUUasw.png" /></figure><p>4. The controller views also ask the stores to keep them notified when state changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*tV7VN0RjpFfwaf1PK3chIA.png" /></figure><h4>The data flow</h4><p>Once the setup is done, the application is ready to accept user input. So let’s trigger an action by having the user make a change.</p><p>We’ll kick off the data flow with a user interaction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*SusQ7Aip2fSWg6raQtPSnA.png" /></figure><p>1. The view tells the action creator to prepare an action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*dkm9qsWuD9DtXzH-u-DjJQ.png" /></figure><p>2. The action creator formats the action and sends it off to the dispatcher.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*fJwvtpq0XQhB4mUZwh7YOQ.png" /></figure><p>3. The dispatcher sends the action off to the stores in sequence. Each store gets notified of all actions. Then the store decides whether it cares about this one or not, and changes the state accordingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*RLrImTDeArSMoA4kZsajLQ.png" /></figure><p>4. Once it’s done changing state, the store lets its subscribed view controllers know.</p><p>5. Those view controllers will then ask the store to give them the updated state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*5SXO2eftdQveFqImGDVB9A.png" /></figure><p>6. After the store gives it the state, the view controller will tell its child views to rerender based on the new state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*fWBaUg9-_1-V5M2YQBWhWg.png" /></figure><p>So that’s how I think of Flux. Hope it helps!</p><h3>Coming up next…</h3><p><a href="https://code-cartoons.com/a-cartoon-intro-to-redux-3afb775501a6#.w36q3cvk6">A cartoon intro to Redux - Code Cartoons</a></p><figure><a href="https://leanpub.com/codecartoons-react"><img alt="" src="https://cdn-images-1.medium.com/max/600/1*b4pDY7WpzfoGJ2IeRnSiYQ.png" /></a></figure><figure><a href="https://tinyletter.com/codecartoons"><img alt="" src="https://cdn-images-1.medium.com/max/250/1*Vhx6UMeHXRPAEOGaPq8vQA.png" /></a></figure><figure><a href="https://twitter.com/codecartoons"><img alt="" src="https://cdn-images-1.medium.com/max/250/1*_oQtFJQYeeOkz4T81Sg4dA.png" /></a></figure><h3>Resources</h3><ul><li><a href="https://facebook.github.io/flux/docs/overview.html">Flux documentation</a></li><li><a href="http://fluxxor.com/what-is-flux.html">Fluxxor documentation</a></li><li><a href="https://medium.com/@dan_abramov/the-case-for-flux-379b7d1982c6">The Case for Flux</a></li></ul><p><em>Thank you to the fantastic </em><a href="https://twitter.com/kentcdodds"><em>Kent C. Dodds,</em></a><em> </em><a href="https://twitter.com/mzabriskie"><em>Matt Zabriskie,</em></a><em> and </em><a href="https://twitter.com/Vjeux"><em>Christopher Chedeau</em></a><em> for their early feedback, and to all the folks at </em><a href="https://twitter.com/brooklyn_js"><em>BrooklynJS</em></a><em> for their comments on the live action version!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6157355ab207" width="1" height="1" alt=""><hr><p><a href="https://medium.com/code-cartoons/a-cartoon-guide-to-flux-6157355ab207">A cartoon guide to Flux</a> was originally published in <a href="https://medium.com/code-cartoons">Code Cartoons</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>