<?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 Dan Abramov on Medium]]></title>
        <description><![CDATA[Stories by Dan Abramov on Medium]]></description>
        <link>https://medium.com/@dan_abramov?source=rss-a3a8af6addc1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xxVEfOOAmIKHWOUloRKLhw.jpeg</url>
            <title>Stories by Dan Abramov on Medium</title>
            <link>https://medium.com/@dan_abramov?source=rss-a3a8af6addc1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 19 Jun 2026 14:34:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dan_abramov/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[Why My New Blog Isn’t on Medium]]></title>
            <link>https://medium.com/@dan_abramov/why-my-new-blog-isnt-on-medium-3b280282fbae?source=rss-a3a8af6addc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b280282fbae</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[blog]]></category>
            <dc:creator><![CDATA[Dan Abramov]]></dc:creator>
            <pubDate>Sun, 17 Feb 2019 00:56:55 GMT</pubDate>
            <atom:updated>2019-02-23T00:18:18.949Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve started a new coding blog in December: <a href="https://overreacted.io/">Overreacted</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YkswLJFKt-PoS9-9YP6uag.png" /><figcaption>overreacted.io</figcaption></figure><p>People often ask why I moved off Medium. Doesn’t it have a better distribution than a personal blog? I’ll answer this question here. My reasons are simple:</p><ol><li><strong>Some of my Medium articles unexpectedly got behind a paywall*.</strong> I’m not sure what happened and whether that’s still the case. But I didn’t do it myself, and that caused a blow to my confidence in Medium as a platform. I respect their need to monetize, but it felt wrong when done retroactively.<br><strong><em>(* Folks from Medium reached out, and it appears that I confused one popup with another. In either case, I’m </em></strong><a href="https://mobile.twitter.com/search?q=paywall%20medium&amp;src=typed_query&amp;f=live"><strong><em>not the only one confused</em></strong></a><strong><em>.)</em></strong></li><li><strong>My views on some topics have changed.</strong> I could continue blogging here but it feels a bit embarrassing to see my old writing just one scroll away. On the other hand, I don’t feel comfortable editing or deleting the old articles. I wanted to start from a clean slate, and this was my way to do it.</li><li><strong>I want to dogfood React. </strong>Just like we heavily use React at Facebook, I’d like to use it more personally. My new blog is built with React. Before you bring out the “blogs don’t need React” pitchfork, consider that in my case using it <em>improves</em> the reader experience. Thanks to <a href="https://www.gatsbyjs.org/">Gatsby</a>, my blog works 100% without JavaScript, loads with a lightning speed, and the client-side JS enhances that experience with prefetching and seamless transitions.</li><li><strong>I like to have full control over the experience.</strong> I like to have a corner of the internet where I can add silly details — such as rendering cups of coffee as a reading time approximation or offering to switch between dark and light themes. In the age of social media and homogeneous pages, it’s fun.</li><li><strong>It’s open to the collaboration.</strong> My blog is <a href="https://github.com/gaearon/overreacted.io">open source</a>. I started getting pull requests from community with fixes to RSS, code highlighting, SEO, and accessibility. What’s more, the React community added the support for translations and started writing them! Overreacted is almost fully <a href="https://overreacted.io/fr/">translated to French</a>, and one article has translations into <a href="https://overreacted.io/why-do-we-write-super-props/">19 languages</a>.</li></ol><p>It feels good to have my own corner of the internet for the first time.</p><p>Even though Medium offers me a huge audience and a better distribution story, I don’t plan to write new articles on Medium.</p><p>See you on <a href="https://overreacted.io/">Overreacted</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b280282fbae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making Sense of React Hooks]]></title>
            <link>https://medium.com/@dan_abramov/making-sense-of-react-hooks-fdbde8803889?source=rss-a3a8af6addc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/fdbde8803889</guid>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Dan Abramov]]></dc:creator>
            <pubDate>Tue, 30 Oct 2018 17:10:55 GMT</pubDate>
            <atom:updated>2018-11-17T02:30:56.273Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>(This article is also </em></strong><a href="https://dev.to/dan_abramov/making-sense-of-react-hooks-2eib"><strong><em>available</em></strong></a><strong><em> on the DEV community without the paywall.)</em></strong></p><p>This week, <a href="https://mobile.twitter.com/sophiebits">Sophie Alpert</a> and I presented the “Hooks” proposal at React Conf, followed by a deep dive from <a href="https://mobile.twitter.com/ryanflorence">Ryan Florence</a>:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fdpw9EHDh2bM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Ddpw9EHDh2bM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fdpw9EHDh2bM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/18155363c13115aea52730d2391542fe/href">https://medium.com/media/18155363c13115aea52730d2391542fe/href</a></iframe><p>I strongly recommend to watch this opening keynote to see the problems we’re trying to solve with the Hooks proposal. However, even an hour is a big time investment, so I decided to share a few thoughts on Hooks below.</p><blockquote><strong>Note: Hooks are an experimental proposal to React. You don’t need to learn about them right now. Also, note that this post contains my personal opinions and doesn’t necessarily reflect the positions of the React team.</strong></blockquote><h3>Why Hooks?</h3><p>We know that components and top-down data flow help us organize a large UI into small, independent, reusable pieces. <strong>However, we often can’t break complex components down any further because the logic is stateful and can’t be extracted to a function or another component.</strong> Sometimes that’s what people mean when they say React doesn’t let them “separate concerns.”</p><p>These cases are very common and include animations, form handling, connecting to external data sources, and many other things we want to do from our components. When we try to solve these use cases with components alone, we usually end up with:</p><ul><li><strong>Huge components</strong> that are hard to refactor and test.</li><li><strong>Duplicated logic</strong> between different components and lifecycle methods.</li><li><strong>Complex patterns</strong> like render props and higher-order components.</li></ul><p>We think Hooks are our best shot at solving all of these problems. <strong>Hooks let us organize the logic <em>inside </em>a component into reusable isolated units:</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=twitter&amp;url=https%3A//twitter.com/threepointone/status/1056594421079261185&amp;image=https%3A//i.embed.ly/1/image%3Furl%3Dhttps%253A%252F%252Fpbs.twimg.com%252Fmedia%252FDqnGs6yWwAAYPXp.jpg%253Alarge%26key%3Da19fcc184b9711e1b4764040d3dc5c07" width="500" height="281" frameborder="0" scrolling="no"><a href="https://medium.com/media/e55e7bcbf2d4912af7e539a2646388e2/href">https://medium.com/media/e55e7bcbf2d4912af7e539a2646388e2/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=twitter&amp;url=https%3A//twitter.com/prchdk/status/1056960391543062528&amp;image=https%3A//i.embed.ly/1/image%3Furl%3Dhttps%253A%252F%252Fpbs.twimg.com%252Ftweet_video_thumb%252FDqsCilOU0AAoS7P.jpg%26key%3Da19fcc184b9711e1b4764040d3dc5c07" width="500" height="281" frameborder="0" scrolling="no"><a href="https://medium.com/media/98fad9dea66efbd9f3d739fd0ce41042/href">https://medium.com/media/98fad9dea66efbd9f3d739fd0ce41042/href</a></iframe><p><strong>Hooks apply the React philosophy (explicit data flow and composition) <em>inside</em> a component, rather than just <em>between</em> the components. </strong>That’s why I feel that Hooks are a natural fit for the React component model.</p><p>Unlike patterns like render props or higher-order components, Hooks don’t introduce unnecessary nesting into your component tree. They also don’t suffer from the <a href="https://reactjs.org/blog/2016/07/13/mixins-considered-harmful.html#why-mixins-are-broken">drawbacks of mixins</a>.</p><p>Even if you have a visceral first reaction (as I did at first!), I encourage you to give this proposal a fair try and play with it. I think you’ll like it.</p><h3>Do Hooks Make React Bloated?</h3><p>Before we look at Hooks in detail, you might be worried that we’re just adding more concepts to React with Hooks. That’s a fair criticism. I think that while there is definitely going to be a short-term cognitive cost to learning them, the end result will be the opposite.</p><p><strong>If the React community embraces the Hooks proposal, it will <em>reduce</em> the number of concepts you need to juggle when writing React applications. </strong>Hooks let you always use functions instead of having to constantly switch between functions, classes, higher-order components, and render props.</p><p>In terms of the implementation size, the Hooks support increases React only by ~1.5kB (min+gzip). While this isn’t much, it’s also likely that <strong>adopting Hooks could <em>reduce</em> your bundle size</strong> because code using Hooks tends to minify better than equivalent code using classes. This example below is a bit extreme but it effectively demonstrates why (click to see the whole thread):</p><iframe src="https://cdn.embedly.com/widgets/media.html?type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=twitter&amp;url=https%3A//twitter.com/jamiebuilds/status/1056015484364087297&amp;image=https%3A//i.embed.ly/1/image%3Furl%3Dhttps%253A%252F%252Fpbs.twimg.com%252Fmedia%252FDqe4XRFX0AADrNS.jpg%253Alarge%26key%3Da19fcc184b9711e1b4764040d3dc5c07" width="500" height="281" frameborder="0" scrolling="no"><a href="https://medium.com/media/40e914f1af8557ee7ecb3709b2be1ebc/href">https://medium.com/media/40e914f1af8557ee7ecb3709b2be1ebc/href</a></iframe><p><strong>The Hooks proposal doesn’t include any breaking changes.</strong> Your existing code would keep on working even if you adopted Hooks in the newly written components. In fact, that’s exactly what we recommend — don’t do any big rewrites! It’s a good idea to wait with adopting Hooks in any critical code. Still, we’d appreciate if you could experiment with the 16.7 alpha to provide us with feedback on the <a href="https://github.com/reactjs/rfcs/pull/68">Hooks proposal</a> and <a href="https://github.com/facebook/react/issues/new">report any bugs</a>.</p><h3>What Are Hooks, Exactly?</h3><p>To understand Hooks, we need to take a step back and think about code reuse.</p><p>Today, there are a lot of ways to reuse logic in React apps. We can write simple functions and call them to calculate something. We can also write components (which themselves could be functions or classes). Components are more powerful, but they have to render some UI. This makes them inconvenient for sharing non-visual logic. This is how we end up with complex patterns like render props and higher-order components. <strong>Wouldn’t React be simpler if there was just <em>one</em> common way to reuse code instead of so many?</strong></p><p>Functions seem to be a perfect mechanism for code reuse. Moving logic between functions takes the least amount of effort. However, functions can’t have local React state inside them. You can’t extract behavior like “watch window size and update the state” or “animate a value over time” from a class component without restructuring your code or introducing an abstraction like Observables. Both approaches hurt the simplicity that we like about React.</p><p>Hooks solve exactly that problem. Hooks let you use React features (like state) from a function — by doing a single function call. React provides a few built-in Hooks exposing the “building blocks” of React: state, lifecycle, and context.</p><p><strong>Since Hooks are regular JavaScript functions, you can combine built-in Hooks provided by React into your own “custom Hooks”.</strong> This lets you turn complex problems into one-liners and share them across your application or with the React community:</p><iframe src="https://cdn.embedly.com/widgets/media.html?type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=twitter&amp;url=https%3A//twitter.com/seldo/status/1057030727512911874&amp;image=https%3A//i.embed.ly/1/image%3Furl%3Dhttps%253A%252F%252Fpbs.twimg.com%252Fprofile_images%252F1023674214304309249%252FzzjjK5xh_400x400.jpg%26key%3Da19fcc184b9711e1b4764040d3dc5c07" width="500" height="281" frameborder="0" scrolling="no"><a href="https://medium.com/media/1222a3fec538e69ddc20489a6ada9a62/href">https://medium.com/media/1222a3fec538e69ddc20489a6ada9a62/href</a></iframe><p>Note that custom Hooks are not technically a React feature. The possibility of writing your own Hooks naturally follows from the way Hooks are designed.</p><h3>Show Me Some Code!</h3><p>Let’s say we want to subscribe a component to the current window width (for example, to display different content on a narrow viewport).</p><p>There are several ways you can write this kind of code today. They involve writing a class, setting up some lifecycle methods, or maybe even extracting a render prop or a higher-order component if you want to reuse it between components. But I think nothing quite beats this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*j8U3U0nZvmEKJrSOK7iH5g.png" /><figcaption><a href="https://gist.github.com/gaearon/cb5add26336003ed8c0004c4ba820eae">https://gist.github.com/gaearon/cb5add26336003ed8c0004c4ba820eae</a></figcaption></figure><p><strong>If you read this code, it does exactly what it says. </strong>We <em>use the window width</em> in our component, and React re-renders our component if it changes.<strong> </strong>And that’s the goal of Hooks — to make components truly declarative even if they contain state and side effects.</p><p>Let’s look at how we could implement this custom Hook. We’d <em>use the React local state</em> to keep the current window width, and <em>use a side effect</em> to set that state when the window resizes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9QhpwSGTKM-c8sc4UNcxqA.png" /><figcaption><a href="https://gist.github.com/gaearon/cb5add26336003ed8c0004c4ba820eae">https://gist.github.com/gaearon/cb5add26336003ed8c0004c4ba820eae</a></figcaption></figure><p>As you can see above, the built-in React Hooks like <em>useState</em> and <em>useEffect</em> serve as the basic building blocks. We can use them from our components directly, or we can combine them into custom Hooks like <em>useWindowWidth</em>. Using custom Hooks feels as idiomatic as using React’s built-in API.</p><p>You can learn more about built-in Hooks from <a href="https://reactjs.org/docs/hooks-overview.html">this overview</a>.</p><p><strong>Hooks are fully encapsulated — each time you call a Hook, it gets isolated local state within the currently executing component.</strong> This doesn’t matter for this particular example (window width is the same for all components!), but it’s what makes Hooks so powerful. They’re not a way to share <em>state</em> — but a way to share <em>stateful logic</em>. We don’t want to break the top-down data flow!</p><p>Each Hook may contain some local state and side effects. You can pass data between multiple Hooks just like you normally do between functions. They can take arguments and return values because they <em>are</em> JavaScript functions.</p><p>Here’s an example of a React animation library experimenting with Hooks:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fppxnl191zx&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fppxnl191zx&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fppxnl191zx%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/82460efcd0258268194cfb8bda917708/href">https://medium.com/media/82460efcd0258268194cfb8bda917708/href</a></iframe><p>Note how in the demo source code, the staggering animation is implemented by passing values through several custom Hooks in the same render function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NJ2G1R_32k95WiPel5JHpg.png" /><figcaption><a href="https://codesandbox.io/s/ppxnl191zx">https://codesandbox.io/s/ppxnl191zx</a></figcaption></figure><p>(If you want to learn more about this example, check out <a href="https://medium.com/@drcmda/hooks-in-react-spring-a-tutorial-c6c436ad7ee4">this tutorial</a>.)</p><p>While it’s not the primary purpose of Hooks, they also open the door for powerful interactive debugging tools:</p><iframe src="https://cdn.embedly.com/widgets/media.html?type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=twitter&amp;url=https%3A//twitter.com/dan_abramov/status/1058837112789839872&amp;image=https%3A//i.embed.ly/1/image%3Furl%3Dhttps%253A%252F%252Fpbs.twimg.com%252Ftweet_video_thumb%252FDrG-htkXcAIFVRQ.jpg%26key%3Da19fcc184b9711e1b4764040d3dc5c07" width="500" height="281" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac729f1b464e11a2516e82d25e667936/href">https://medium.com/media/ac729f1b464e11a2516e82d25e667936/href</a></iframe><p>The ability to pass data between Hooks make them a great fit for expressing animations, data subscriptions, form management, and other stateful abstractions. <strong>Unlike render props or higher-order components, Hooks don’t create a “false hierarchy” in your render tree.</strong> They’re more like a flat list of “memory cells” attached to a component. No extra layers.</p><h3>So What About Classes?</h3><p>Custom Hooks are, in our opinion, the most appealing part of the Hooks proposal. But in order for custom Hooks to work, React needs to provide functions with a way to declare state and side effects. And that’s exactly what built-in Hooks like <em>useState</em> and <em>useEffect</em> let us do. You can learn about them in the <a href="https://reactjs.org/docs/hooks-overview.html">documentation</a>.</p><p>It turns out that these built-in Hooks aren’t <em>only</em> useful for creating custom Hooks. They are <em>also</em> sufficient for defining components in general, as they provide us with all the necessary features like state. This is why we’d like Hooks to become the primary way to define React components in the future.</p><p>We have no plans to deprecate classes. At Facebook we have tens of thousands of class components and, like you, we have no intention of rewriting them. But if the React community embraces Hooks, it doesn’t make sense to have two different recommended ways to write components. Hooks can cover all use cases for classes while providing more flexibility in extracting, testing, and reusing code. This is why Hooks represent our vision for the future of React.</p><h3>But Aren’t Hooks Magic?</h3><p>You may have been surprised by the <a href="https://reactjs.org/docs/hooks-rules.html">Rules of Hooks</a>.</p><p><strong>While it’s unusual that Hooks have to be called at the top level, you probably wouldn’t want to define state in a condition even if you could.</strong> For example, you can’t define state conditionally in a class either, and over four years of talking to React users I haven’t heard a complaint about this.</p><p>This design is crucial to enabling custom Hooks without introducing extra syntactic noise or other pitfalls. We recognize the initial unfamiliarity but we think this tradeoff is worth the features it enables. If you disagree, I encourage you to play with it in practice and see if that changes how you feel.</p><p>We’ve been using Hooks in production for a month to see whether engineers get confused by these rules. We found that in practice people get used to them in a matter of hours. Personally, I admit that these rules “felt wrong” to me at first too, but I quickly got over it. This experience mirrored my first impression with React. (Did you like React immediately? I didn’t until my second try.)</p><p>Note that there is no “magic” in the implementation of Hooks either. As Jamie <a href="https://mobile.twitter.com/jamiebuilds/status/1055538414538223616">points out</a>, it looks pretty similar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xNeUnpwUvFMuQu9Zr6A3AA.jpeg" /><figcaption><a href="https://gist.github.com/gaearon/62866046e396f4de9b4827eae861ff19">https://gist.github.com/gaearon/62866046e396f4de9b4827eae861ff19</a></figcaption></figure><p>We keep a list of Hooks per component, and move to the next item in the list whenever a Hook is used. Thanks to the Rules of Hooks, their order is the same on every render, so we can provide the component with correct state for each call. Don’t forget that React doesn’t need to do anything special to know which component is rendering — React <em>is</em> what’s calling your component.</p><p>(<a href="https://medium.com/@ryardley/react-hooks-not-magic-just-arrays-cd4f1857236e">This article by Rudi Yardley</a> contains a nice visual explanation!)</p><p>Perhaps you’re wondering where React keeps the state for Hooks. The answer is it’s kept in the exact same place where React keeps state for classes. React has an internal update queue which is the source of truth for any state, no matter how you define your components.</p><p>Hooks don’t rely on Proxies or getters which can be common in modern JavaScript libraries. So arguably Hooks are <em>less</em> magic than some popular approaches to similar problems. I’d say Hooks are about as much magic as calling <em>array.push</em> and <em>array.pop</em> (for which the call order matters too!)</p><p>The design of Hooks isn’t tied to React. In fact, during the first few days after the proposal was published, different people came up with experimental implementations of the same Hooks API for Vue, Web Components, and even plain JavaScript functions.</p><p>Finally, if you’re a functional programming purist and feel uneasy about React relying on mutable state as an implementation detail, you might find it satisfactory that handling Hooks could be implemented in a pure way using algebraic effects (if JavaScript supported them). And of course React has always relied on mutable state internally — precisely so that <em>you</em> don’t have to.</p><p>Whether you were concerned from a more pragmatic or a dogmatic perspective (if you were at all), I hope that at least one of these justifications makes sense. If you’re curious, Sebastian (the author of the Hooks proposal) also responded to these and other concerns in <a href="https://github.com/reactjs/rfcs/pull/68#issuecomment-439314884">this comment</a> on the RFC. Most importantly, I think Hooks let us build components with less effort, and create better user experiences. And that’s why I’m personally excited about Hooks.</p><h3>Spread Love, Not Hype</h3><p>If Hooks still don’t seem compelling to you, I can totally understand it. I still hope that you’ll give them a try on a small pet project and see if that changes your opinion. Whether you haven’t experienced the problems Hooks solve, or if you have a different solution in mind, please let us know in the RFC!</p><p>If I <em>did</em> get you excited, or at least a little bit curious, that’s great! I have just one favor to ask. There are many folks who are learning React right now, and they will get confused if we hurry with writing tutorials and declaring best practices for a feature that has barely been out for a few days. There are some things about Hooks that aren’t quite clear yet even to us on the React team.</p><p><strong>If you create any content about Hooks while they’re unstable, please mention prominently that they are an experimental proposal, and include a link to the </strong><a href="https://reactjs.org/hooks"><strong>official documentation</strong></a><strong>.</strong> We’ll keep it up to date with any changes to the proposal. We’ve also spent quite a bit of effort to make it comprehensive, so many questions are already answered there.</p><p>When you talk to other people who aren’t as excited as you are, please be courteous. If you see a misconception, you can share extra information if the other person is open to it. But any change is scary, and as a community we should try our best to help people instead of alienating them. And if I (or anyone else on the React team) fail to follow this advice, please call us out!</p><h3>Next Steps</h3><p>Check out the documentation for Hooks proposal to learn more about it:</p><ul><li><a href="https://reactjs.org/docs/hooks-intro.html">Introducing Hooks</a> (motivation)</li><li><a href="https://reactjs.org/docs/hooks-overview.html">Hooks at a Glance</a> (walkthrough)</li><li><a href="https://reactjs.org/docs/hooks-custom.html">Building Your Own Hooks</a> (that’s the fun part)</li><li><a href="https://reactjs.org/docs/hooks-faq.html">Hooks FAQ</a> (it’s likely your question is answered there!)</li></ul><p>Hooks are still in an early stage, but we’re excited to hear feedback from all of you. You can direct it to the <a href="https://github.com/reactjs/rfcs/pull/68">RFC</a>, but we’ll also do our best to keep up with the conversations on Twitter.</p><p>Please let me know if something isn’t clear, and I’d be happy to chat about your concerns. Thank you for reading!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_XMyHqfFSyw03BiNjBoV3Q.jpeg" /><figcaption>Vitra — Portemanteau Hang it all</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fdbde8803889" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[You Might Not Need Redux]]></title>
            <link>https://medium.com/@dan_abramov/you-might-not-need-redux-be46360cf367?source=rss-a3a8af6addc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/be46360cf367</guid>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Dan Abramov]]></dc:creator>
            <pubDate>Mon, 19 Sep 2016 21:30:45 GMT</pubDate>
            <atom:updated>2016-09-19T21:30:45.266Z</atom:updated>
            <content:encoded><![CDATA[<p>People often choose Redux before they need it. “What if our app doesn’t scale without it?” Later, developers frown at the indirection Redux introduced to their code. “Why do I have to touch three files to get a simple feature working?” Why indeed!</p><p>People blame Redux, React, functional programming, immutability, and many other things for their woes, and I understand them. It is natural to compare Redux to an approach that doesn’t require “boilerplate” code to update the state, and to conclude that Redux is just complicated. In a way it is, and by design so.</p><p>Redux offers a tradeoff. It asks you to:</p><ul><li>Describe application state as plain objects and arrays.</li><li>Describe changes in the system as plain objects.</li><li>Describe the logic for handling changes as pure functions.</li></ul><p>None of these limitations are required to build an app, with or without React. In fact these are pretty strong constraints, and you should think carefully before adopting them even in parts of your app.</p><p>Do you have good reasons for doing so?</p><p>These limitations are appealing to me because they help build apps that:</p><ul><li><a href="https://egghead.io/lessons/javascript-redux-persisting-the-state-to-the-local-storage?course=building-react-applications-with-idiomatic-redux">Persist state to a local storage and then boot up from it, out of the box.</a></li><li><a href="http://redux.js.org/docs/recipes/ServerRendering.html">Pre-fill state on the server, send it to the client in HTML, and boot up from it, out of the box.</a></li><li><a href="https://github.com/dtschust/redux-bug-reporter">Serialize user actions and attach them, together with a state snapshot, to automated bug reports, so that the product developers can replay them to reproduce the errors.</a></li><li><a href="https://github.com/philholden/redux-swarmlog">Pass action objects over the network to implement collaborative environments without dramatic changes to how the code is written.</a></li><li><a href="http://redux.js.org/docs/recipes/ImplementingUndoHistory.html">Maintain an undo history or implement optimistic mutations without dramatic changes to how the code is written.</a></li><li><a href="https://github.com/gaearon/redux-devtools">Travel between the state history in development, and re-evaluate the current state from the action history when the code changes, a la TDD.</a></li><li><a href="https://github.com/romseguy/redux-devtools-chart-monitor">Provide full inspection and control capabilities to the development tooling so that product developers can build custom tools for their apps.</a></li><li><a href="https://youtu.be/gvVpSezT5_M?t=11m51s">Provide alternative UIs while reusing most of the business logic.</a></li></ul><p>If you’re working on <a href="https://hyperterm.org/">an extensible terminal</a>, <a href="https://hacks.mozilla.org/2016/09/introducing-debugger-html/">a JavaScript debugger</a>, or <a href="https://twitter.com/necolas/status/727538799966715904">some kinds of webapps</a>, it might be worth giving it a try, or at least considering some of its ideas (they are <a href="https://github.com/evancz/elm-architecture-tutorial">not</a> <a href="https://github.com/omcljs/om">new</a>, by the way!)</p><p>However, if you’re just learning React, don’t make Redux your first choice.</p><p>Instead learn to <a href="https://facebook.github.io/react/docs/thinking-in-react.html">think in React</a>. Come back to Redux if you find a real need for it, or if you want to try something new. But approach it with caution, just like you do with any highly opinionated tool.</p><p>If you feel pressured to do things “the Redux way”, it may be a sign that you or your teammates are taking it too seriously. It’s just one of the tools in your toolbox, <a href="https://www.youtube.com/watch?v=xsSnOQynTHs">an experiment</a> <a href="https://www.youtube.com/watch?v=uvAXVMwHJXU">gone wild</a>.</p><p>Finally, don’t forget that you can apply ideas from Redux without using Redux. For example, consider a React component with local state:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ab96fca83d8d0afe750a5e1b36744d7/href">https://medium.com/media/7ab96fca83d8d0afe750a5e1b36744d7/href</a></iframe><p>It is <em>perfectly fine </em>as it is. Seriously, it bears repeating.</p><p><em>Local state is fine.</em></p><p>The tradeoff that Redux offers is to <em>add indirection </em>to decouple “what happened” from “how things change”.</p><p>Is it always a good thing to do? No. It’s a tradeoff.</p><p>For example, we can extract a reducer from our component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cda37d0dffa92367bb2d5d60513d1658/href">https://medium.com/media/cda37d0dffa92367bb2d5d60513d1658/href</a></iframe><p>Notice how we just used Redux without running <em>npm install.</em> Wow!</p><p>Should you do this to your stateful components? Probably not. That is, <em>not unless you have a plan</em> to benefit from this additional indirection. Having a plan is, in the parlance of our times, the 🔑.</p><p><a href="http://redux.js.org/">Redux library</a> itself is only a set of helpers to “mount” reducers to a single global store object. You can use as little, or as much of Redux, as you like.</p><p>But if you trade something off, make sure you get something in return.</p><p>⚛</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be46360cf367" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Asking Good Questions]]></title>
            <link>https://medium.com/@dan_abramov/asking-good-questions-421f08ee7e5c?source=rss-a3a8af6addc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/421f08ee7e5c</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Dan Abramov]]></dc:creator>
            <pubDate>Mon, 04 Jul 2016 21:14:14 GMT</pubDate>
            <atom:updated>2016-07-04T22:39:39.001Z</atom:updated>
            <content:encoded><![CDATA[<p>I receive programming questions on Twitter, GitHub, email, and other channels. I try to answer them when I can. Lately I haven’t been able to do that very well because I’m a human and don’t scale.</p><p>For personal questions, I maintain an AMA. If you want to know my favorite Pokémon, <a href="https://github.com/gaearon/ama/">ask a question or read the answers</a>!</p><p>If you have a programming question, read on.</p><h4>“Hello, World” Questions</h4><p>If you can’t get React to render a “hello, world” example or if your Redux counter doesn’t update when you press “+” and you’re stuck, you can message me directly on Twitter with that question.</p><p>I still encourage you to try asking on <a href="http://stackoverflow.com/">StackOverflow</a> and <a href="http://www.reactiflux.com/">Reactiflux Discord</a> first. I often find that <a href="https://en.wikipedia.org/wiki/Rubber_duck_debugging">writing up the question makes it clear in my head</a>, and the solution becomes obvious. But if you’re just making first steps and are really confused by something, I can definitely take a quick glance.</p><p>Please make sure to share what you’ve tried on GitHub, <a href="https://gist.github.com/">Gist</a>, or, better yet, a <a href="http://jsfiddle.net/reactjs/69z2wepo/">fiddle</a> before asking. This way we can make this a quick interaction instead of a back-and-forth. Otherwise it can be time consuming for both of us, especially due to different timezones.</p><p>Is your question more complex than a “hello, world”? Read on.</p><h4>More Complex Questions</h4><p>If your question is specific (e.g. something doesn’t work) and more complex than getting “Hello, world” running, please post it to StackOverflow first. I stopped answering such questions directly in messages because every time I get the same question I regret not having a link to my last answer.</p><p>If you send me a StackOverflow question in a message or in mentions, I will try to take a look at it and tell you if I can answer it. Which brings me to the next point.</p><h4>How to Get Upvotes</h4><p>The tricky part about <a href="http://stackoverflow.com/help/how-to-ask">asking good questions</a> is to strike a balance between sharing too few and too many details. You need to <strong>phrase your question in a way that both explains <em>your</em> problem and sounds generic enough that other people find it useful</strong>. Browsing <a href="http://stackoverflow.com/questions/tagged/reactjs?sort=votes&amp;pageSize=50">popular questions</a> for any given tag can give you a good idea of what this looks like. It is a challenge! But if it is hard to ask a question, imagine what it’s like to answer it.</p><p>Nobody likes to invest 5 minutes into reading a question only to realize that it omits the part of the code that is crucial to understanding the problem. However, it is equally frustrating to read through 500 lines of code most of which are irrelevant to the issue.</p><p>It takes experience and care to ask good questions. You’ll get better at it. For now, <strong>it is enough that you </strong><a href="http://sscce.org/"><strong>make an effort</strong></a>. Here’s how I do it.</p><h4>Isolating the Issue</h4><p>Take the code that you have issues with, switch to another branch, and start removing parts that you suspect are irrelevant. Are you seeing the issue with a particular component? Render this component on the page alone. Is the issue still reproducible? Good. If not, bring the removed parts back one by one until you see which one causes the issue. Then isolate that part.</p><p>Next, remove all the irrelevant details from the buggy module itself. Keep removing the styling, markup, and business logic until the issue no longer reproduces. <strong>Eliminate as many dependencies as possible</strong>. Get to the absolute minimum code necessary to reproduce the issue.</p><p>Don’t forget to commit regularly! Otherwise you might remove too much and the issue might no longer reproduce. Make sure you always have a breadcrumb trail of what you have been doing.</p><p>Finally, try to recreate the issue in another environment. It’s handy to have a <a href="http://jsfiddle.net/reactjs/69z2wepo/">“base fiddle”</a> using the same libraries as your project does. This way you can quickly create small independent snippets of code and paste the relevant parts of your project into them. There are some new services similar to <a href="http://jsfiddle.net">jsfiddle</a> but that provide access to npm modules. In particular, I heard good things about <a href="http://www.webpackbin.com/">WebpackBin</a> and <a href="https://esnextb.in/">ESNextbin</a>. Check them out!</p><p>Most importantly, don’t give up too easily. <strong>There is a reason behind every issue.</strong> It can be a bug, a typo, or just a misunderstanding. Take comfort in the thought that this reason <em>exists</em>, and keep eliminating possible causes.</p><p>Experts often don’t know the problem any better than you. What they learned is <em>not</em> to trust themselves. They dig deeper and keep reducing the test case even if nothing obvious jumps at them for several hours. They know there is a problem somewhere, and finding it is a boring, mind-numbing but usually finite process.</p><p>If you’re debugging a problem late in the evening, drop it and sleep on it. Sleep deprivation makes it far too easy to miss typos and other simple mistakes.</p><p>You shouldn’t drive yourself to the point of despair either. If you’re stuck and you’ve exhausted your patience trying to isolate the problem, ask for help.</p><h4>Linking to GitHub Projects</h4><p>If you have no luck recreating the issue in a fiddle, it is fine to link to a GitHub project from a StackOverflow question. The chance that you will get a good reply is considerably slimmer but it’s worth trying as the last resort.</p><p>Here’s a few tips to make your chance of getting a good reply higher:</p><ul><li><strong>Delete any unrelated files from the repository. </strong>Your project should build but if there is just one screen you’d like people to look at, delete all the others. You still need to trim down the reproducing case even if you share it on GutHub.</li><li><strong>Make sure all dependencies are specified in <em>package.json</em>.</strong> Imagine somebody wants to help you so much they clone your project, wait 15 minutes for <em>npm install</em> to finish, and then realize the project won’t start due to unspecified dependencies. To mitigate this, delete <em>node_modules</em>, run <em>npm install</em> yourself, and make sure the project starts swimmingly. If you forgot a dependency, add it to <em>package.json</em> and try again until it works.</li><li><strong>Make sure <em>npm start</em> will start your project.</strong> You can control what <em>npm start</em> does using the <a href="https://docs.npmjs.com/misc/scripts"><em>scripts</em> field</a> in <em>package.json. </em>It could be something as simple as <em>“start”: “gulp”</em>. The important part is that the person answering the question shouldn’t have to guess your bundler or task manager. All such tools should be dependencies in <em>package.json.</em></li><li><strong>Don’t assume other people have Grunt/Gulp/Webpack/Browserify installed globally. </strong>You might have run <em>npm install -g grunt</em> at some point but many people don’t do this, or have different versions. <a href="https://firstdoit.com/no-need-for-globals-using-npm-dependencies-in-npm-scripts-3dfb478908#.malhol96h">Use npm scripts so that you don’t need to ask people to install and run global commands.</a></li><li><strong>Provide clear instructions to reproduce the issue in README.</strong> This is crucial. There is nothing like cloning a project, installing it, running it, opening it in the browser, and then having no idea how to reproduce the issue, or what the expected behavior is. Instead, you want to specify the exact sequence of steps (e.g. “npm start, open browser at this address, click on this button, I expected X to happen but Y happened instead”).</li></ul><p>It is also a good etiquette to <a href="http://meta.stackexchange.com/questions/18669/should-posts-be-self-contained">never delete the repository</a> if you used it in a StackOverflow question.</p><h4>Abstract Questions</h4><p>Finally, there are a few questions that I can’t really give a good answer to.</p><p><strong>“What is better, X or Y?”</strong></p><p>Unless I used both of these solutions (highly unlikely), I’m not qualified to answer. Even if I used them both, the most I can share is a personal anecdote, not a verdict. My experience will be very specific to the project that I worked on. It is most likely outdated and might not apply to your project because we had different constraints and requirements.</p><p>Another problem is in the way this question is phrased. I always feel like the person asking it is trying to avoid a technical decision by delegating it to an “authority” (me in this case). I refuse to be an authority and I don’t want to be held responsible for other people’s choices. People also drastically overestimate how much I know. I’m clueless about a wide range of topics.</p><p>Instead, you can ask: “Have you worked with X or Y? If so, did you like either?” If I reply “No, but X looks cool” it doesn’t mean the project is good for you. It just means I liked its README.</p><p>Does this sound like useless advice? I think it is! The only way to find if something works for you is to create a small project with it, not to ask me about it.</p><p><strong>“What are your thoughts on X?”</strong></p><p>If I’ve never used X, I don’t have any thoughts on it besides “I kinda like it” or “I kinda dislike it”. Neither will be very useful to you, and knowing my opinion might even discourage you from going with a good choice. You have much more context about your problem than I do.</p><p>If I used X, I have more impressions than I can fit in a tweet. I don’t quite understand how to respond to this question on Twitter. I could write an essay in response but this would quickly become a full-time job.</p><p>If you’d like to engage me in a discussion about X, I’m happy to participate if I’ve used it. But let’s talk about something specific, not “my thoughts”. <strong>My thoughts are not interesting. Instead, I would like to hear about <em>your experiences</em> using it.</strong></p><p>Finally, perhaps you built X. This is awesome! Help me and others understand what it is and why you built it. Explain not just what the API looks like, but how and why you are using it.</p><p>README is the best place to do this. Your tweets to me will get lost tomorrow. As much as I’d like to help, I probably don’t understand your use case well enough so my opinion won’t be very useful to you. Instead, seek out the people having the same problem, and ask their opinions.</p><h4>Wrapping Up</h4><p>Try to put yourself in the shoes of the person answering the question. You might discover that some questions are impossible to answer, or that you could have spent more effort crafting the question to get a better answer. Let’s value each others’ time and have more high quality conversations!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=421f08ee7e5c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hot Reloading in React]]></title>
            <link>https://medium.com/@dan_abramov/hot-reloading-in-react-1140438583bf?source=rss-a3a8af6addc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/1140438583bf</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Dan Abramov]]></dc:creator>
            <pubDate>Tue, 08 Mar 2016 21:21:49 GMT</pubDate>
            <atom:updated>2016-04-18T15:01:59.269Z</atom:updated>
            <content:encoded><![CDATA[<h4>or, an Ode to Accidental Complexity</h4><p><em>Note: </em><a href="https://github.com/gaearon/react-hot-boilerplate/pull/61"><em>React Hot Loader 3</em></a><em>, released a month after I published this article, solves most of the problems described in this post. Give it a try!</em></p><p><a href="https://github.com/gaearon/react-transform-boilerplate">React Transform</a> is an experimental project I started after giving the <a href="https://www.youtube.com/watch?v=xsSnOQynTHs">Hot Reloading with Time Travel</a> talk at React Europe.</p><p>My goal was to bring a live editing environment that preserves component state and handles errors gracefully to as many React users as possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*9epU6txsWWSY6lI1OHaqgg.gif" /><figcaption>OK, this demo is not very interesting. You’ll have to trust me that it works on real projects too 😎</figcaption></figure><p>By all reasonable metrics, <a href="http://npm-stat.com/charts.html?package=babel-plugin-react-transform&amp;author=&amp;from=&amp;to=">React Transform has been a success</a>. If anything, it proved the demand for a better development experience.</p><p>I would even say it has been <em>way</em> too popular for such an experimental and unpolished piece of software. This caused some pain for the people who felt pressured to adopt it and experienced problems with configuration.</p><p>I am sorry about this, as I had no time to focus on the experience of <em>setting up</em> the tool. There were, and still are, too many low level problems that need to be solved first before addressing the high level problems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sooa5DscnxZIK3zvhcXEVw.png" /></figure><p>In fact I’ve come to realize that it is not a viable solution in the long term, and I plan to sunset React Transform in a few months in favor of a different project. You might think I have a habit of <a href="https://medium.com/@dan_abramov/the-death-of-react-hot-loader-765fa791d7c4">killing off my projects</a> after they become successful. I assure you that this is not the case.</p><p>In this post, I will explain how I came to this conclusion, as well as describe my journey in understanding how hot reloading can be implemented, and the challenges I faced, in more detail than I did before. I hope this will be helpful to anyone who is curious where the magic comes from.</p><p>The underlying problem is that I’m inexperienced and I experiment in the open. If I make a mistake, it takes me some time to see that mistake for what it is, and even more time to come up with a solution.</p><p>React Transform is a mixed bag. It has some good ideas, but also has a bunch of fundamental problems. The good news is that I think these problems are soluble.</p><p>But first, let’s turn to the past.<br>It’s going to take <em>quite a while</em> so grab some snacks 😉</p><p>Trigger warning: accidental complexity.</p><h3>Disclaimer</h3><p>Today I will not discuss any tools that integrate with the browser engine. Personally, I am only interested in “userland” hot reloading technology. If you see this as an artificial limitation, you might be interested in <a href="http://amokjs.com">Amok</a>. It can do some incredible things like replacing functions inside closures thanks to its integration with the browser engine.</p><p>There are also some projects that use some of the hot reloading code I released under the hood but differ in their approaches to some questions. For example, <a href="https://github.com/milankinen/livereactload">LiveReactload</a> is a separate project but it shares some parts of its implementation with React Transform. I’m not going to discuss such projects in this post as I only can tell you about my experience and the problems I have personally encountered.</p><p>I am also not going to spend time discussing hot reloading tools for compile-to-JS languages such as <a href="https://github.com/bhauman/lein-figwheel">Figwheel</a> and <a href="https://github.com/elm-lang/elm-reactor">Elm Reactor</a>. Their existence and simplicity is a big inspiration to me but at the moment I am primarily interested in the JavaScript tools that I can use in the existing React projects today.</p><p>JavaScript brings unique constraints that these tools don’t need to handle. Whether those constraints are enough to stop trying, or present an interesting challenge, can be described as a pure function of your convictions, determination, and time.</p><h3>React Hot Loader</h3><p><a href="https://github.com/gaearon/react-hot-loader/">React Hot Loader</a> was my first popular open source project and, to my knowledge, the first tool that allowed you to edit React component files without losing the state or unmounting the components.</p><h4>How It Started</h4><p>Like many other projects, React Hot Loader started <a href="http://stackoverflow.com/questions/24581873/what-exactly-is-hot-module-replacement-in-webpack">with a question</a>. I saw that Webpack Hot Module Replacement and React can be combined together in an interesting way, and I was excited.</p><p>You might have seen the video I used to introduce React Hot Loader:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F100010922&amp;url=https%3A%2F%2Fvimeo.com%2F100010922&amp;image=http%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F481366230_960.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=vimeo" width="1252" height="720" frameborder="0" scrolling="no"><a href="https://medium.com/media/22cd4fd69a18716a0b2e23d4f22400e9/href">https://medium.com/media/22cd4fd69a18716a0b2e23d4f22400e9/href</a></iframe><p>The truth is it predates the real React Hot Loader. It was recorded at 6a.m. the day (or, rather, the night) I got the proof of concept working, and it relied on some horrible global variables I put inside the React source code just to record the video. Of course I didn’t tell that to anyone 😉.</p><p>I did not expect a lot of feedback but after Christopher Chedeau retweeted it my Twitter notifications went through the roof. I went from 12 to a 100 Twitter followers in a day so I knew people were as excited about it as I was.</p><p>I figured that I needed to turn this into a real project on a vacation, and that’s how React Hot Loader came to be a few weeks later.</p><h4>First Attempt: Using HMR Directly</h4><p>Before React Hot Loader, my first thought was that I could use Webpack HMR to replace the root component of my app and re-render it with React.</p><p>Note that HMR is not specific to React at all. James Long explains HMR well in <a href="http://jlongster.com/Backend-Apps-with-Webpack--Part-III">this article</a>. Basically it’s just a way for modules to say “When a new version of some module I import is available, run a callback in my app so I can do something with it”. This happens every time you save a file when HMR is enabled.</p><p>A vanilla HMR implementation of hot reloading a React app looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ef67b7ae7b2bb4d0af750566efccb12/href">https://medium.com/media/4ef67b7ae7b2bb4d0af750566efccb12/href</a></iframe><p>As long as you configure Webpack to enable HMR, the code above works fine and redraws your application when a hot reload occurs without refreshing the browser.</p><p><strong>This implementation doesn’t use React Hot Loader, React Transform, or anything else—it’s just vanilla Webpack HMR API. </strong>It does not change the semantics of your React components. HMR is just a fancy way to poll the development server, inject <em>&lt;script&gt;</em> tags with the updated modules, and run a callback in your existing code.</p><p>Updates to nested components work because of how Webpack HMR API is designed. If a module does not specify how to handle updates to itself, the modules that imported it also get included in the hot update bundle, and the updates “bubble up” until they are all <em>accepted</em> by all the modules importing them. If some of the modules don’t end up being accepted, the hot update fails and a warning is printed. To “accept” a dependency, you just call <em>module.hot.accept(‘./name’, callback)</em> which Webpack parses at compile time.</p><p>Because we accept updates to <em>App.js</em> inside <em>index.js</em>, we also implicitly accept updates to anything imported from the <em>App.js</em>—such as other components.</p><p>For example, let’s say that I edit a <em>Button.js </em>component which is imported by <em>UserProfile.js</em> and <em>NavBar.js</em>. Let’s also say that those modules, in turn, are both imported by <em>App.js</em>.</p><p>Because <em>index.js </em>is the only module importing <em>App.js</em> and it includes a <em>module.hot.accept(‘./App’, callback) </em>handler, Webpack will generate an “update bundle” with all those files and then run the <em>callback </em>we supplied<strong>.</strong></p><p>When we get an updated <em>App.js</em>, we just want to re-render the React app:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c4d1cd593bf8ebfb8242e02215b2247/href">https://medium.com/media/1c4d1cd593bf8ebfb8242e02215b2247/href</a></iframe><p>Problem solved?</p><p>In a way, yes.<br>But not really.</p><p>I told you it’s a long story! 🙅</p><h4>Problem: DOM and Local State are Destroyed</h4><p>When I say “next version of a module” I just mean that the module code is evaluated again in another<em> &lt;script&gt;</em> tag.</p><p>Because the <em>App.js</em> module gets re-evaluated, the class identity does not match the previous component class. So <em>NextApp !== App</em> even though technically they represent different “versions” of the same component.</p><p>As far as React is concerned, you’re trying to render a completely different type of component, so React will unmount the previous one. This makes sense: React can’t magically “change” the type of existing instances to a new class even if it wanted to!</p><p>This is why, with the approach described above, React destroys both the DOM and the local state of your components.</p><h4>Possible Solution: Externalize the State</h4><p>James Kyle recently <a href="https://twitter.com/thejameskyle/status/700003791874060288">pointed out</a> that apps with a single state tree, such as Redux apps, don’t benefit as much from preserving the component local state. Often all you really need in such apps is to hold onto the external state tree.</p><p>In Redux apps, the complexity of preserving the local React component state might not be worth it because most of the state we’d like to keep in such apps is outside the components anyway.</p><p>Inspired by the conversation with him, I prepared <a href="https://github.com/reactjs/redux/pull/1455">this PR</a> that removes React Transform from Redux examples in favor of vanilla HMR API.</p><p>James also suggested that you can use <a href="https://github.com/chromakode/isolated-core">isolated-core</a> for such cases. I haven’t looked at it yet, but I suggest you to check out <a href="https://github.com/thejameskyle/isolated-core-demo/blob/master/src/app.js#L9-L21">isolated-core-demo</a> if you are interested in this approach.</p><p>You can even have a decent development experience with full reloading when you have a single state tree. For example, you can save the Redux state to <em>localStorage</em> in development, read it before initializing the store so even <em>Cmd+R</em> doesn’t wipe it out, and call it a day.</p><p>Many apps can’t afford or don’t want to hold state in a single atom, and I think this is fine. I happen to think that we should not give up on preserving React local state just because some people don’t need it. 😉</p><p>However if you <em>do</em> use something like Redux, I <a href="https://github.com/reactjs/redux/pull/1455">strongly suggest you to consider using vanilla HMR API</a> instead of React Hot Loader, React Transform, or other similar projects. It’s just so much simpler—at least, it is today.</p><h4>Preserving the DOM and Local State</h4><p>Now you see why naïvely replacing a React component with a re-evaluated version of it destroys the DOM and state of the existing instances.</p><p>I see two different ways to fix this:</p><ol><li>Devise a way to detach React instances from DOM nodes and state, create the new instances of the new component types, and somehow “attach” them to the existing DOM and state recursively.</li><li>Alternatively, proxy component types so that the types that React <em>sees</em> stay the same, but the actual <em>implementations</em> change to refer to the new underlying component type on every hot update.</li></ol><p>Please let me know if you are aware of any other solutions.</p><h4>Failed Attempt: Rehydrating the Tree</h4><p>The first approach is probably better in the long term but React currently provides no capabilities to (de)hydrate the state of React tree and replace the instances without destroying the DOM and running the lifecycle hooks. Even if we reached into the private React APIs to accomplish this, we would still face subtle problems with the first approach.</p><p>For example, React components often subscribe to Flux stores and other sideways data sources in <em>componentDidMount. </em>Even if we had a way to silently replace old instances with the new instances without destroying their DOM or state, the old instances would still keep their existing subscriptions, and the new instances would not be subscribed at all.</p><p>To subscribe the new instances, we would need to also fire lifecycle hooks on the them during the replacement operation. However then <em>componentDidMount</em> would run twice for the same DOM nodes which might break some assumptions that React components tend to make. In case of third-party components, you wouldn’t even be able to work around those assumptions because it is not your code!</p><p>Ultimately, the first approach probably be more feasible if React state subscriptions were declarative and independent of the lifecycle hooks, or if React did not rely so hard on classes and instances. Both may be the case in the future versions of React, but we’re not there yet.</p><h4>Successful Attempt: Proxying Component Classes</h4><p>The second approach is the one I use in React Hot Loader and React Transform. It is fairly invasive and changes semantics of your code but it gets the job done with today’s React, both in greenfield and legacy React applications. In most cases, it works great.</p><p>The idea is that every React component class gets wrapped into a “proxy”. In this case, I don’t mean an <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Proxy">ES2015 Proxy</a> although I’m definitely <a href="https://github.com/gaearon/react-proxy/issues/40">looking forward to using it instead of an ad-hoc approach I came up with</a>.</p><p>Those proxies are just classes that act just like <em>your</em> classes<em> </em>but provide you the hooks to inject the new implementation of the class, at which point <em>the existing instances</em> start to act like the new version of the class. This way both React local state and DOM are preserved.</p><h4>Problem in Retrospect: Lack of Tests</h4><p>There are <a href="https://github.com/gaearon/react-proxy/tree/1.x/test">many non-trivial parts</a> to creating a correct proxy, and React Hot Loader didn’t do it well because it didn’t have any tests. New versions of React used to break it all the time, and not writing a comprehensive test suite is the mistake I regret the most about React Hot Loader.</p><p>My latest work on proxying React components is available as a library called <a href="https://github.com/gaearon/react-proxy">React Proxy</a>. It is extensively tested, used inside React Transform but is low-level enough to be used separately. It only implements proxies for React components so it doesn’t depend on either Webpack or Babel. For example, I’m aware of people using it inside Electron apps as well as inside big projects with custom build systems.</p><h4>Problem: Where to Wrap Components in Proxies?</h4><p>Fun trivia: React Hot Loader is not a “loader” because it implements hot reloading. This is a common misconception. 😀</p><p>It is a “loader” because that’s how Webpack refers to what other bundlers call “transforms”. For example, <a href="https://github.com/webpack/json-loader">json-loader</a> transforms JSON files to JavaScript modules, and <a href="https://github.com/webpack/style-loader">style-loader</a> transforms CSS files into JavaScript code that injects them as stylesheets.</p><p>Similarly, React Hot Loader is also a <a href="https://github.com/gaearon/react-hot-loader/blob/7b0bc31d0a65eeae2742579e12ab10cf43df1af6/index.js#L26-L72">compile time transform</a>, and a rather dumb one. It wraps every React component that <a href="https://github.com/gaearon/react-hot-loader/blob/7b0bc31d0a65eeae2742579e12ab10cf43df1af6/makeExportsHot.js#L21">it finds in <em>module.exports</em></a><em> </em>into a proxy, and exports the proxied components instead.</p><p>With this approach, when <em>&lt;App&gt;</em> renders <em>&lt;NavBar&gt;</em>, it really renders <em>&lt;NavBarProxy&gt; </em>(you wouldn’t know it though!)<em> </em>that calls <em>NavBar#render() </em>from its <em>render()</em> method and changes the internal reference to the newest version of <em>NarBar </em>whenever an updated <em>NavBar.js</em> module executes.</p><p>The proxies are stored globally by reasonably-unique IDs derived from the filename and displayName of the component classes. When an updated class is evaluated, the matching proxy is updated to “absorb” the new version of the class, and the components re-render without losing the local state or the DOM.</p><p>Looking for components in <em>module.exports</em> sounds like a reasonable approach at first. Developers usually keep every component in its own file anyway so naturally all components are exported. However, as time went by, and especially as new approaches became adopted by React community, I discovered some problems inherent to this approach:</p><ul><li>As <a href="https://medium.com/@dan_abramov/mixins-are-dead-long-live-higher-order-components-94a0d2f9e750">higher order components</a> became popular, people started to export the higher level component wrappers instead of the actual components they write. As a result, React Hot Loader didn’t “see” the inner components in <em>module.exports </em>and didn’t create proxies for them. Their DOM and local state would get destroyed on every change to the file. This is especially frustrating for higher order components that provide styling such as <a href="https://github.com/jsstyles/react-jss">React JSS</a>.</li><li>React 0.14 introduced functional components which encourage micro-componentization inside a single file. Even if React Hot Loader inspected <em>toString()</em> of exported functions, looked for <em>createElement()</em> calls and assumed that these functions are React components, it still wouldn’t “see” the local components that aren’t exported. Those components would not become wrapped in proxies, and thus would cause the entire subtrees below them to lose both DOM and state. This jeopardizes the whole idea of preserving the state because it makes it extremely fragile.</li></ul><p>Merely asking developers to export those “hidden” components isn’t enough because they are referenced inside the file! If we want to use the proxies, we have to somehow make sure that even references <em>inside</em> the file refer to those proxies instead of the actual components, which we obviously can’t do by overwriting <em>module.exports</em>.</p><p>At this point many people were saying: forget about it. Just use a global state solution and don’t attempt to preserve the local state.</p><p>Maybe I should have listened 😉.</p><h4>Problem: Webpack Dependency</h4><p>This was a big one. Webpack at the time was the only JavaScript bundler that implemented HMR. React Hot Loader proxy logic was not coupled to it but it wasn’t properly separated either. And of course React Hot Loader itself was a Webpack loader, first and foremost.</p><p>I worried: what if other bundlers don’t implement HMR? What if Webpack dies and gets replaced by something else? What about React Native which has been <a href="https://github.com/mjohnston/react-native-webpack-server">notoriously difficult</a> to make friends with Webpack?</p><p>My intention was to at least make it <em>possible</em> for somebody else to use my work outside of Webpack—even if they had to also spend some time to hook that solution up to their bundler.</p><h3>React Transform</h3><p>About the time that I wrote <a href="https://medium.com/@dan_abramov/the-death-of-react-hot-loader-765fa791d7c4">The Death of React Hot Loader</a> I was looking for ways to fix those problems.</p><p>Babel took the JavaScript world by storm, and I needed <em>some </em>kind of static analysis to locate and wrap the React components even if they are not exported directly. Babel seemed like a good fit for that.</p><p>Additionally, I was looking for a way to implement error handling. Hot reloading wasn’t very useful when every error thrown inside <em>render() </em>threw React into an invalid state, and I wanted to fix that.</p><p>Both wrapping component in a proxy and wrapping component’s <em>render() </em>in a <em>try / catch</em> sounded like “function that takes a component class and does something with it” to me.</p><p>So I thought: why not create a Babel plugin that locates React components in your codebase and wraps them in arbitrary customizable transforms?</p><p>Wouldn’t it be cool if other people created other developer-time transforms, for example, to overlay components with performance heatmaps?</p><p>This is how React Transform came to be.</p><h4>First Approach: Modularity Overkill</h4><p>I wasn’t sure which projects and ideas would still be relevant after a while so I decided to take an opposite approach to React Hot Loader. Instead of just one, I created five different projects under the “React Transform” umbrella:</p><ul><li><a href="https://github.com/gaearon/react-proxy">React Proxy</a> implements low-level proxies for React components.</li><li><a href="https://github.com/gaearon/react-transform-hmr">React Transform HMR</a> creates a proxy for a passed component and keeps a list of proxies on a global object so they are updated when the transform is called again for the same component.</li><li><a href="https://github.com/gaearon/react-transform-catch-errors">React Transform Catch Errors</a> wraps the <em>render()</em> method in a <em>try / catch</em> and displays a configurable component instead if there is an error.</li><li><a href="https://github.com/gaearon/babel-plugin-react-transform">Babel Plugin for React Transform</a> does its best to find all React components in your codebase, extract information about them at compile time, and wrap them in the transforms that you chose (e.g. React Transform HMR).</li><li><a href="http://github.com/gaearon/react-transform-boilerplate">React Transform Boilerplate</a> showed how these technologies work together.</li></ul><h4>Problem: Too Many Moving Parts</h4><p>This approach became both a blessing, as it allowed easier experimentation, and a curse, as end users were increasingly confused about how those projects relate to each other. There were too many moving parts exposed to the user: “proxies”, “HMR”, “hot middleware”, “error catcher”, etc.</p><p>I made a mistake of hoping Babel 6 would come out soon with “presets” and I’d just be able to ship a preset with the preconfigured sane defaults.</p><p>However Babel 6 release came much later than I expected. (I’m not complaining because it was a terrifically complex release and Sebastian was burned out from the project, and did his very best in shipping it, for which I am very grateful.)</p><p>React Transform become popular way faster than I expected, and the complicated config I hoped would go away soon kept multiplying in the boilerplate projects, confusing new users. The fact that we included it in Redux examples made it even worse.</p><p>When Babel 6 came out, it turns out that the plugin needed a rewrite because I didn’t really know how to write Babel plugins and did it very sloppily. Luckily, James Kyle graciously rewrote it completely for v2.0 before ultimately deciding that the project is a bad idea and resigning from participating in it. Good thing he realized this <em>after</em> writing a v2.0! 😁</p><h4>Solution: Sane Defaults</h4><p>After the Babel 6 update and publishing <a href="https://github.com/danmartinez101/babel-preset-react-hmre">an official preset</a>, the modularity no longer was such a problem, and actually became useful because different environments (e.g. React Native) were able to take the parts they cared about. The lesson I learned is that any time you modularize something, you have to provide a good “default” interface for it. Those who are interested in the internal dependencies and customization will find them anyway.</p><h4>Problem: Higher Order Components Strike Again</h4><p>When you solve an issue, try not to introduce the opposite issue.</p><p>React Hot Loader could see anything you export from a file but couldn’t see the “local” components declared inside it. For example, React Hot Loader would find the exported component generated by <em>useSheet() </em>higher order component and update the <em>styles</em> on change, but it would not “see” the <em>Counter </em>itself, and for this reason its state would get reset when the file is saved:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9dcf3f2870a44a9b085e7f69c53089c4/href">https://medium.com/media/9dcf3f2870a44a9b085e7f69c53089c4/href</a></iframe><p>React Transform “fixed” this by finding component declarations with static analysis, looking for classes that inherit from <em>React.Component </em>or are declared using <em>React.createClass()</em>.</p><p>Guess what it’s missing? The exported components! In this example, React Transform would preserve the state of the <em>Counter</em> component and hot reload changes to its <em>render()</em> and <em>handleClick()</em> methods, but any changes to the <em>styles</em> would not get reflected because it doesn’t know that <em>useSheet(styles)(Counter)</em> happens to also <em>return</em> a React component that needs to be proxied.</p><p>Most commonly people <a href="https://github.com/gaearon/babel-plugin-react-transform/issues/26">discover this problem</a> when they notice that their selectors and action creators in Redux are no longer hot reloaded. This is because React Transform does not realize that <em>connect()</em> returns a component, and there is no easy way to tell it.</p><h4>Problem: Compile to JS Languages Don’t Babel</h4><p>Naturally, using a Babel plugin excludes users of the compile-to-JS languages. Even if we told them to use Babel as part of their toolchain, we would still not be able to reliably find their class abstractions because of what they compile to. Sure, technically <a href="https://github.com/gaearon/babel-plugin-react-transform/pull/77/files">anything is possible</a> but supporting this would probably be a nightmare because we would be relying on implementation details of third-party compilers.</p><h4>Problem: Wrapping Components Statically Is Invasive</h4><p>Finding classes that inherit from <em>React.Component </em>or created using <em>React.createClass()</em> is <a href="https://github.com/gaearon/babel-plugin-react-transform/blob/19c714643faad916f3342f34171f8974589835e1/src/index.js#L4-L32">not too hard</a> by itself. However it is potentially error prone, and you really don’t want to <a href="https://github.com/gaearon/babel-plugin-react-transform/issues/78">introduce false positives</a> here.</p><p>With React 0.14, the task is even harder. <em>Any</em> function that returns a valid <em>ReactElement</em> is potentially a component. But you can’t be sure so you have to apply heuristics. For example, you can decide that any function in the top-level scope that is named in <em>PascalCase</em>, uses JSX and accepts no more than two arguments, is probably a React component. Are you going to get some false positives? Yea, probably.</p><p>Bad. Even worse, now you have to teach every “transform” to deal both with classes and functions. What if React introduces <a href="https://github.com/reactjs/react-future/blob/7ce26f52d53e5132238a4bfcbab821ad77e89d0c/04%20-%20Layout/prototype/index.js">yet another way</a> to declare components in v16? Would we have to rewrite all the transforms?</p><p>Finally, <em>actually wrapping</em> things statically is pretty complicated. You have to handle all the myriad ways of the way functions and classes can be exported in JavaScript, including default and named exports, function declarations, arrow functions, class declarations, class expressions, <em>createClass()</em> calls, and so on. In each case you need to find a way to bind a different value to the same variable or expression without screwing it up.</p><p>Introducing support for functional components has been <a href="https://github.com/gaearon/babel-plugin-react-transform/issues/57">the most requested feature</a> in React Transform but I just don’t see it happening at this point because of the complexity it would impose on the project and its maintainers, and the potential for breakage due to edge cases.</p><p>Shall we give up at this point?</p><h3>The Road Ahead</h3><p>I still see both React Hot Loader and React Transform as successful projects despite their inherent flaws and limitations. I believe that great hot reloading experience can be achieved in React, and that we shouldn’t stop trying. In fact, it’s the first time in months that I felt optimistic about hot reloading React components.</p><p>React Native ships a hot reloading implementation based on React Transform very soon. It’s stable enough for now, but I also believe that we need a better and simpler solution looking forward.</p><p>Below I will describe this solution the way I see it.</p><h4>Solution: Use Vanilla HMR If You Can</h4><p>This is a straightforward one.</p><p>As James Kyle suggested, if you keep all your state in a single store like Redux, and don’t care too much about preserving the DOM on reloads, <a href="https://github.com/reactjs/redux/pull/1455">consider dropping React Transform and using vanilla HMR</a> or something like <a href="https://github.com/thejameskyle/isolated-core-demo">isolated-core</a>.</p><p>It will make your project simpler!</p><h4>Solution: Drop Configurable Transforms</h4><p>Configurable transforms were useful while React Native shipped with a fork of React and didn’t have an HMR implementation, but now it works with <em>react</em> package as is, and implements the necessary subset of HMR as well.</p><p>Browserify also now has an <a href="https://github.com/AgentME/browserify-hmr">HMR plugin</a> which, admittedly, is not bug-free, but I feel much more comfortable about using HMR as the “default” in the project. I think at this point it’s fair to ask other environments to polyfill it like React Native did.</p><p>React plans to ship an <a href="https://github.com/facebook/react/issues/5306">official instrumentation API</a> that makes use cases like profiling or inspecting components much easier to implement in userland without resorting to wrapping them. In fact, doing this via DevTools API will be much more reliable, as the instrumentation code would be separated from the running application.</p><p>This is why I think the idea of highly configurable third-party transforms was a fundamentally flawed one, and we need to drop it. Let’s focus on hot reloading instead.</p><h4>Solution: Use Error Boundaries</h4><p>React v15 ships with an initial implementation of <a href="https://github.com/facebook/react/issues/2461">error boundaries</a> which let components up the tree catch and display errors that occurred while rendering the components below the tree.</p><p>Effectively this means that wrapping components’ <em>render()</em> methods in <em>try / catch </em>blocks should no longer be necessary because you can implement your own <em>&lt;CatchErrors&gt;</em> component and put it at the top of your hierarchy and display errors like React Native does. We’ll probably ship such component together with the future hot reloading solution.</p><h4>Solution: Proxy at the Call Site</h4><p>I believe this to be the missing piece and the biggest mistake I made with React Transform. In fact Sebastian Markbåge told me in October that he wasn’t quite impressed with my Babel plugin but I didn’t understand his advice fully until I re-evaluated it a few days ago. The solution was right under my nose all this time.</p><p>Finding and wrapping React components in the source is hard to do, and is potentially destructive. This really might break your code.</p><p>On the other hand, <em>tagging</em> them is relatively safe. Imagine a Babel plugin that adds something like <em>register(uniqueId, Component)</em> at the end of the every module for anything that looks <em>remotely</em> like a component. For example, we can do this for every top-level function, class, and export:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8abd1c1962af6a3b48acb2d88984b87b/href">https://medium.com/media/8abd1c1962af6a3b48acb2d88984b87b/href</a></iframe><p>What would <em>register()</em> do, then? The implementation I have in mind will check whether the passed value at least a function, and if it is, will create a React Proxy around it. It will not, however, replace your class or function! This is the important bit. The proxy will just sit in a global map, patiently waiting until you use… <em>React.createElement()</em>.</p><p>If we got to <em>React.createElement()</em>, it’s the proof that whatever you pass there as a type really <em>is</em> a React component, no matter how it was declared.</p><p>As long as React Proxy supports all types of components (and it already supports both classes and functions), we should be fine. This is why we monkeypatch <em>React.createElement()</em> to refer to our internal map and to use the proxy instead of the passed type. It might look roughly like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6bf0d48b879f93c710fac56682e1a9c6/href">https://medium.com/media/6bf0d48b879f93c710fac56682e1a9c6/href</a></iframe><p>With some changes to React Proxy necessary to get <em>instanceof </em>and similar checks right both inside and outside the component module, we should be able to get a reasonable approximation of the hot reloading behavior React Transform currently supports, and solve its many issues at the same time:</p><ul><li>There won’t be any false positives for components because wrapping occurs only for what is actually <em>used</em> as a component.</li><li>We can “find” functions, classes, <em>createClass()</em> calls, and every export, and we don’t need to worry about writing complicated tree traversal logic to wrap different things correctly.</li><li>Changing functional components will not reset the DOM or the state of the children trees.</li><li>We can release React Hot Loader 2.0 that uses the same technique under the hood, but without the static analysis. It would only work for exported components, but this will be immediately useful to the compile-to-JS languages which are currently not supported by React Transform at all.</li><li>The generated code would be easier to work with because we can move the generated lines at the end of the file instead of polluting the code like React Transform currently does.</li></ul><p>I might be wrong here, and there still might be some problems that I missed, but overall this seems like a big step in the right direction to me, and all the groundwork like having a good proxy implementation or the code to find the <em>createClass()</em> calls is already done. We just need to remove the parts we don’t need, such as wrapping, and fix the edge cases.</p><p>If you plan to work on something like this, please let me know so I can help. If you don’t, well, I work at Facebook now, so maybe I can spend some time on this as well 😀.</p><p>Hopefully, with all the lessons learned, we’ll have better tooling for hot reloading in 2016. Once we get the low level implementation right, we can make the setup experience user-friendly. And someday we’ll clean up these hacks, and make React friendlier to hot reloading out of the box. But for now, being a step ahead of the accidental complexity is good enough to me.</p><h4>A Little Update</h4><p><a href="https://github.com/gaearon/react-hot-boilerplate/pull/61">Say hi to React Hot Loader 3.</a></p><p>⚛</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1140438583bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Components, Elements, and Instances]]></title>
            <link>https://medium.com/@dan_abramov/react-components-elements-and-instances-90800811f8ca?source=rss-a3a8af6addc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/90800811f8ca</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Dan Abramov]]></dc:creator>
            <pubDate>Mon, 14 Dec 2015 18:28:45 GMT</pubDate>
            <atom:updated>2015-12-15T16:12:55.973Z</atom:updated>
            <content:encoded><![CDATA[<p>Many people get confused by <strong>the difference between components, their instances, and elements in React</strong>. Why are there three different terms to refer to something that is painted on screen?</p><p>If you’re new to React, you probably only worked with component classes and instances before. For example, you may declare a Button<em> component </em>by creating a class. When the program is running, you may have several <em>instances </em>of this component on screen, each with its own properties and local state. This is the traditional object oriented UI programming. Why introduce <em>elements</em>?</p><p>In this traditional UI model, it is up to you take care of creating and destroying child component instances. If a <em>Form</em> component wants to render a <em>Button</em> component, it needs to create its instance, and manually keep it up to date with any new information.</p><pre><strong>class</strong> Form <strong>extends</strong> TraditionalObjectOrientedView {<br>  render() {<br><em>    // Read some data passed to the view</em><br>    <strong>const</strong> { isSubmitted, buttonText } = <strong>this</strong>.attrs;</pre><pre>    <strong>if</strong> (!isSubmitted &amp;&amp; !<strong>this</strong>.button) {<br>      <em>// Form is not yet submitted. Create the button!</em><br>      <strong>this</strong>.button = <strong>new</strong> Button({<br>        children: buttonText,<br>        color: &#39;blue&#39;<br>      });<br>      <strong>this</strong>.el.appendChild(<strong>this</strong>.button.el);<br>    }</pre><pre>    <strong>if</strong> (<strong>this</strong>.button) {<br><em>      // The button is visible. Update its text!<br></em>      <strong>this.</strong>button.attrs.children = buttonText;<br>      <strong>this</strong>.button.render();<br>    }</pre><pre>    <strong>if</strong> (isSubmitted &amp;&amp; <strong>this</strong>.button) {<br>      <em>// Form was submitted. Destroy the button!</em><br>      <strong>this</strong>.el.removeChild(<strong>this</strong>.button.el);<br>      <strong>this</strong>.button.destroy();<br>    }</pre><pre><strong>    if </strong>(isSubmitted &amp;&amp; !<strong>this</strong>.message) {<br>      <em>// Form was submitted. Show the success message!</em><br>      <strong>this</strong>.message = <strong>new</strong> Message({ text: &#39;Success!&#39; });<br>      <strong>this</strong>.el.appendChild(<strong>this</strong>.message.el);<br>    }<br>  }<br>}</pre><p>This is pseudocode, but this is more or less what you end up with when you try to write composable UI that behaves consistently in an object oriented way with a framework like Backbone.</p><p>Each component has to keep references to its DOM node and to the instances of the children components, and create, update, and destroy them when the time is right. The lines of code grow as the square of the number of possible states of the component, and the parents have direct access to their children component instances, making it hard to decouple them in the future.</p><p>Now let’s talk about React.</p><p>In React, this is where the <em>elements</em> come to rescue. <strong>An element is a plain object <em>describing</em> a component instance or DOM node and its desired properties. </strong>It contains only information about the component type (for example, a <em>Button</em>), its properties (for example, its <em>color</em>), and any child elements inside it.</p><p>An element is not an actual instance. Rather, it is a way to tell React what you <em>want</em> to see on the screen. You can’t call any methods on the element. It’s just an immutable description object with two fields: <strong>type: (string | Component)</strong> and <strong>props: Object</strong>.*</p><p>When the element’s <strong>type</strong> is a string, an element represents a DOM node with that tag name, and <strong>props </strong>correspond to its attributes. This is what React will render. For example:</p><pre>{<br>  type: &#39;button&#39;,<br>  props: {<br>    className: &#39;button button-blue&#39;,<br>    children: {<br>      type: &#39;b&#39;,<br>      children: &#39;OK!&#39;<br>    }<br>  }<br>}</pre><p>Such an element is just a way to represent this HTML as a plain object:</p><pre>&lt;button class=&#39;button button-blue&#39;&gt;<br>  &lt;b&gt;<br>    OK!<br>  &lt;/b&gt;<br>&lt;/button&gt;</pre><p>Note how the elements can be nested. By convention, when we want to create an element tree, we specify one or more child elements as the <strong>children</strong> prop of their containing element.</p><p>What’s important is that both child and parent elements are <em>just descriptions and not actual instances.</em> They don’t refer to anything on the screen when you create them. You can create them and throw them away, and it won’t matter much.</p><p>React Elements are easy to traverse, don’t need to be parsed, and of course are much lighter than the actual DOM elements—they’re just objects!</p><p>However, the <strong>type</strong> of an element can also be a function or class corresponding to a React component:</p><pre>{<br>  type: Button,<br>  props: {<br>    color: &#39;blue&#39;,<br>    children: &#39;OK!&#39;<br>  }<br>}</pre><p>This is the core idea of React.</p><p><strong>An element describing a component is also an element, just like an element describing the DOM node. They can be nested and mixed with each other.</strong></p><p>This feature lets you define a <em>DangerButton</em> component as a <em>Button</em> with a specific <em>color</em> property value without worrying about whether <em>Button </em>renders to a <em>button</em>, a <em>div</em>, or something else entirely.</p><pre><strong>const</strong> DangerButton = ({ children }) =&gt; ({<br>  type: Button,<br>  props: {<br>    color: &#39;red&#39;,<br>    children: children<br>  }<br>});</pre><p>You can mix and match them later:</p><pre><strong>const</strong> DeleteAccount = () =&gt; ({<br>  type: &#39;div&#39;,<br>  props: {<br>    children: [{<br>      type: &#39;p&#39;,<br>      props: {<br>        children: &#39;Are you sure?&#39;<br>      }<br>    }, {<br>      type: DangerButton,<br>      props: {<br>        children: &#39;Yep&#39;<br>      }<br>    }, {<br>      type: Button,<br>      props: {<br>        color: &#39;blue&#39;,<br>        children: &#39;Cancel&#39;<br>      }<br>   }]<br>});</pre><p>Or, if you prefer JSX:</p><pre><strong>const</strong> DeleteAccount = () =&gt; (<br>  &lt;div&gt;<br>    &lt;p&gt;Are you sure?&lt;/p&gt;<br>    &lt;DangerButton&gt;Yep&lt;/DangerButton&gt;<br>    &lt;Button color=&#39;blue&#39;&gt;Cancel&lt;/Button&gt;<br>  &lt;/div&gt;<br>);</pre><p>This keeps components decoupled from each other, as they can express both <em>is-a</em> and <em>has-a</em> relationships exclusively through composition.</p><p>When React sees an element with a function or class <strong>type</strong>, it will know to ask <em>that</em> component what element it renders to with the given <strong>props</strong>.</p><p>When it sees</p><pre>{<br>  type: Button,<br>  props: {<br>    color: &#39;blue&#39;,<br>    children: &#39;OK!&#39;<br>  }<br>}</pre><p>React will ask <em>Button</em> what it renders to, and it will get</p><pre>{<br>  type: &#39;button&#39;,<br>  props: {<br>    className: &#39;button button-blue&#39;,<br>    children: {<br>      type: &#39;b&#39;,<br>      children: &#39;OK!&#39;<br>    }<br>  }<br>}</pre><p>React will repeat this process until it knows the underlying DOM tag elements for every component on the page.</p><p>React is like a child asking “what is Y” for every “X is Y” you explain to them until they figure out every little thing in the world.</p><p>Remember the <em>Form</em> example above? It can be written in React as follows*:</p><pre><strong>const</strong> Form = ({ isSubmitted, buttonText }) =&gt; {<br>  <strong>if</strong> (isSubmitted) {<br><em>    // Form submitted! Return a message element.<br></em>    <strong>return</strong> {<br>      type: Message,<br>      props: {<br>        text: &#39;Success!&#39;<br>      }<br>    };<br>  }</pre><pre><em>  // Form still visible! Return a button element.</em><br>  <strong>return </strong>{<br>    type: Button,<br>    props: {<br>      children: buttonText,<br>      color: &#39;blue&#39;<br>    }<br>  };<br>};</pre><p>That’s it! For a React component, props are the input, and an element tree is the output.</p><p><strong>The returned element tree can contain both elements describing DOM nodes, and elements describing other components. This lets you compose independent parts of UI without relying on their internal DOM structure.</strong></p><p>We let React create, update, and destroy instances. We <em>describe</em> them with elements we return from the components, and React takes care of managing the instances.</p><p>In the code above, <em>Form</em>, <em>Message</em>, and <em>Button</em> are React components. They can either be written as functions, as above, or as classes descending from <em>React.Component</em>:</p><pre><strong>class</strong> Button <strong>extends</strong> React.Component {<br>  render() {<br>    <strong>const</strong> { children, color } = <strong>this</strong>.props;</pre><pre><em>    // Return an element describing a<br>    // &lt;button&gt;&lt;b&gt;{children}&lt;/b&gt;&lt;/button&gt;</em></pre><pre>    <strong>return</strong> {<br>      type: &#39;button&#39;,<br>      props: {<br>        className: &#39;button button-&#39; + color,<br>        children: {<br>          type: &#39;b&#39;,<br>          props: {<br>            children: children<br>          }<br>        }<br>      }<br>    };<br>  }<br>}</pre><p>When a component is defined as a class, it is a little more powerful than a functional component. It can store some local state and perform custom logic when the corresponding DOM node is created or destroyed. A functional component is less powerful but is simpler, and it acts like a class component with just a single <em>render()</em> method.</p><p><strong>However, whether functions or classes, fundamentally they are all components to React. They take the props as their input, and return the elements as their output.</strong></p><p>When you call</p><pre>ReactDOM.render({<br>  type: Form,<br>  props: {<br>    isSubmitted: <strong>false</strong>,<br>    buttonText: &#39;OK!&#39;<br>  }<br>}, <strong>document</strong>.getElementById(&#39;root&#39;));</pre><p>React will ask the <em>Form</em> component what element tree it returns, given those props. It will gradually “refine” its understanding of your component tree in terms of simpler primitives:</p><pre><em>// React: You told me this...</em><br>{<br>  type: Form,<br>  props: {<br>    isSubmitted: <strong>false,<br>    </strong>buttonText: &#39;OK!&#39;<br>  }<br>}</pre><pre><em>// React: ...And Form told me this...</em><br>{<br>  type: Button,<br>  props: {<br>    children: &#39;OK!&#39;,<br>    color: &#39;blue&#39;<br>  }<br>}</pre><pre><em>// React: ...and Button told me this! I guess I&#39;m done.</em><br>{<br>  type: &#39;button&#39;,<br>  props: {<br>    className: &#39;button button-blue&#39;,<br>    children: {<br>      type: &#39;b&#39;,<br>      props: {<br>        children: &#39;OK!&#39;<br>      }<br>    }<br>  }<br>}</pre><p>At the end of this process React knows the result DOM tree, and a renderer like <em>ReactDOM</em> or <em>React Native</em> applies the minimal set of changes necessary to update the actual DOM nodes.</p><p>This gradual refining process is also the reason React apps are easy to optimize. If some parts of your component tree become too large for React to visit efficiently, you can tell it to <a href="https://facebook.github.io/react/docs/advanced-performance.html">skip this “refining” and diffing certain parts of the tree if the relevant props have not changed</a>. It is very fast to calculate whether the props have changed if they are immutable, so React and immutability work great together, and can provide great optimizations with the minimal effort.</p><p>You might have noticed that I have talked a lot about components and elements, and not so much about the instances. The truth is, instances have much less importance in React than in most object oriented UI frameworks.</p><p>Only components declared as classes have instances, and you never create them directly: React does that for you. While there are mechanisms for a parent component instance to access a child component instance, they are only used for imperative actions (such as setting focus on a field), and should generally be avoided.</p><p>React will take care of creating an instance for every class component, so that you can write components in an object oriented way with methods and local state, but other than that, instances are not very important in the React’s programming model, and are managed by React itself.</p><h3>Recap</h3><p><em>An element</em> is a plain object describing what you want to appear on the screen in terms of the DOM nodes or other components. Elements can contain other elements in their props.</p><p>A <em>component</em> can be two things. It can be a class with a <em>render() </em>method that inherits from <em>React.Component</em> . Or it can be a function. In both cases, it takes props as an input, and returns an element tree as the output.</p><p>When a component receives some props as an input, it is because a parent component returned an element with its type and these props. This is why people say that the props flows one way in React: from parents to children.</p><p>An <em>instance</em> is what you refer to as <strong>this</strong> in the component class you write. It is useful for storing local state and reacting to the lifecycle events.</p><p>Functional components don’t have instances at all. Class components have instances, but you never need to create a component instance directly—React takes care of this.</p><p>Finally, to create elements, use <em>React.createElement(), </em>JSX, or an element factory helper. I discourage you from writing them as plain objects in the real code—just know that they are plain objects under the hood.</p><h3>Further Reading</h3><ul><li><a href="https://facebook.github.io/react/blog/2014/10/14/introducing-react-elements.html">Introducing React Elements</a></li><li><a href="https://facebook.github.io/react/blog/2015/02/24/streamlining-react-elements.html">Streamlining React Elements</a></li><li><a href="https://facebook.github.io/react/docs/glossary.html">React (Virtual) DOM Terminology</a></li></ul><h3>Footnotes</h3><blockquote>* All React elements <a href="https://github.com/facebook/react/pull/4832">require an additional $$typeof: Symbol.for(‘react.element’) field on the object for the security reasons</a>. I am omitting it in the examples above. Generally you should either use JSX or React.createElement() so don’t worry about it. I wanted to give you an idea about the raw API, so I wrote the objects inline, but to run this code, you need to add $$typeof to each of them.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90800811f8ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Use Classes and Sleep at Night]]></title>
            <link>https://medium.com/@dan_abramov/how-to-use-classes-and-sleep-at-night-9af8de78ccb4?source=rss-a3a8af6addc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/9af8de78ccb4</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[class]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Dan Abramov]]></dc:creator>
            <pubDate>Sat, 10 Oct 2015 01:09:34 GMT</pubDate>
            <atom:updated>2015-10-10T01:17:27.868Z</atom:updated>
            <content:encoded><![CDATA[<p>There is a growing sentiment in the JavaScript community that ES6 classes are <a href="https://github.com/joshburgess/not-awesome-es6-classes/">not awesome</a>:</p><ul><li>Classes obscure the prototypal inheritance at the core of JS.</li><li>Classes encourage inheritance but you should prefer composition.</li><li>Classes tend to lock you into the first bad design you came up with.</li></ul><p>I think it’s great that the JavaScript community is paying attention to the problems caused by the use of classes and inheritance, but I’m worried that the beginners are confused as classes are both “bad” and were just added to the language. Even more confusingly, some libraries, notably React, use ES6 classes all over its documentation. Is React intentionally following “bad practices”?</p><p>I think we’re in a weird transitional period where the widespread usage of classes is a necessary evil because they are <em>limiting</em>. They are certainly better than learning a new ad-hoc class system that comes with every framework, each with its own way of multiple inheritance in form of mixins.</p><p>If you like functional programming, you might see how transitioning from proprietary class systems to the “stripped down” ES6 classes (no mixins, no autobinding, etc) moves us a step closer towards the functional solutions.</p><p>In the meantime, here is how to use classes and sleep at night:</p><ul><li><strong>Resist making classes your public API. </strong>(Of course exporting React components is an exception as they aren’t used directly.) You can always hide your classes behind the factory functions. If you expose them, people will inherit from them in all sorts of ways that make zero sense to you, but that you may break in the future. Avoiding breaking people’s classes is hard because they might use the method names you want to use in the future versions, they might read your private state, they might put their own state onto your instances, and they might override your methods without calling <em>super</em> which may work for a while if they’re lucky but break later. That said, when there isn’t back-and-forth interaction between the base class and the user’s derived classes, such as in case of React components, exposing a base class may very well be a valid API choice.</li><li><strong>Don’t inherit more than once.</strong> Inheritance can be handy as a shortcut, and inheriting once is um-kay, but don’t go deeper. The problem with inheritance is that the descendants have too much access to the implementation details of every base class in the hierarchy, and vice versa. When the requirements change, refactoring a class hierarchy is so hard that it turns into a WTF sandwich with traces of outdated requirements. Instead of creating a class hierarchy, consider creating several factory functions. They may call each other in chain, tweaking the behavior of each other. You may also teach the “base” factory function to accept a “strategy” object modulating the behavior, and have the other factory functions provide it. Regardless of the approach you choose, the important part is to keep inputs and outputs explicit at every step. “You need to override a method” is not an explicit API and is hard to design well, but “you need to provide a function as an argument” is explicit and helps you think it through.</li><li><strong>Don’t make <em>super </em>calls from methods.</strong> If you override a method in a derived class, override it completely. Tracing a sequence <em>super</em> calls is like following a series of notes hidden around the world by a movie villain. It’s only fun when you watch someone else doing it. What if you <em>really</em> need to transform the result of the super method, or perform it before or after doing something else? See the previous point: turn your classes into the factory functions and keep the relationships between them very explicit. When your only tools are parameters and return values, it’s easier to discover the right balance of responsibilities. The intermediate functions can have different (and more fine-grained) interfaces than the “top-level” and “bottom-level” functions. Classes don’t easily provide such mechanisms because you can’t designate a method “for the use of base class only” or “for the use of derived class only”, but functional composition makes it natural.</li><li><strong>Don’t expect people to use your classes.</strong> Even if you choose to provide your classes as a public API, prefer duck typing when accepting inputs. Instead of <em>instanceof</em> checks, assert the existence of the methods you plan to use, and trust the user to do the right thing. This will make userland extensions and later tweaks easier, as well as eliminate the issues with iframes and different JavaScript execution contexts.</li><li><strong>Learn functional programming.</strong> It will help you not <em>think</em> in classes, so you won’t be compelled to use them even though you know their pitfalls.</li></ul><h3>So What About React Components?</h3><p>I hope that the rules above show why this is a <em>terrible</em> idea:</p><pre><strong>import</strong> { Component } from &#39;react&#39;;</pre><pre><strong>class</strong> BaseButton <strong>extends</strong> Component {<br>  componentDidMount() {<br>    console.log(&#39;hey&#39;);<br>  }</pre><pre>  render() {<br>    <strong>return</strong> &lt;button&gt;{<strong>this</strong>.getContent()}&lt;/button&gt;;<br>  }<br>}</pre><pre><strong>class</strong> RedButton <strong>extends</strong> BaseButton {<br>  componentDidMount() {<br>    <strong>super</strong>.componentDidMount();<br>    console.log(&#39;ho&#39;);<br>  }</pre><pre>  getContent() {<br>    <strong>return</strong> &#39;I am red&#39;;<br>  }</pre><pre>  render() {<br>    <strong>return</strong> (<br>      &lt;div className=&#39;red&#39;&gt;<br>        {<strong>super</strong>.render()}<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><p>However I say that the code below is <em>just</em> <em>fine.</em></p><pre><strong>import</strong> { Component } from &#39;react&#39;;</pre><pre><strong>class</strong> Button <strong>extends</strong> Component {<br>  componentDidMount() {<br>    console.log(&#39;hey&#39;);<br>  }</pre><pre>  render() {<br>    <strong>return</strong> (<br>      &lt;div className={<strong>this</strong>.props.color}&gt;<br>        &lt;button&gt;{<strong>this</strong>.props.children}&lt;/button&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><pre><strong>class</strong> RedButton <strong>extends</strong> Component {<br>  componentDidMount() {<br>    console.log(&#39;ho&#39;);<br>  }</pre><pre>  render() {<br>    <strong>return</strong> (<br>      &lt;Button color=&#39;red&#39;&gt;<br>        I am red<br>      &lt;/Button&gt;<br>    );<br>  }<br>}</pre><p>Yes, we used the dreaded <em>class</em> keyword but we didn’t create a hierarchy, as we always extended <em>Component. </em>And you can write lint rules for that, if you wish so. There is no need to jump through the hoops just to avoid using the <em>class</em> keyword in the code above. It’s not a real issue.</p><p>When you want to supply a component with some additional functionality in a generic way, <a href="https://medium.com/@dan_abramov/mixins-are-dead-long-live-higher-order-components-94a0d2f9e750">higher order components</a> cover pretty much every use case I have encountered so far. Technically they are just <a href="https://en.wikipedia.org/wiki/Higher-order_function">higher order functions</a>.</p><p>After discovering higher order components, I haven’t felt the need for either <em>createClass()</em>-style mixins, proposed-for-ES7 mixins, <a href="https://github.com/stampit-org/react-stampit/blob/master/docs/composition.md">“stamp composition”</a>, or any other composition solution. This is another argument in favor of just using <em>class — </em>because you don’t realistically need anything “more powerful”.</p><p>As of React 0.14 you can write the components as <a href="https://github.com/reactjs/react-future/blob/master/01%20-%20Core/03%20-%20Stateless%20Functions.js">pure functions</a>. This is totally worth doing. Any time you can write a function instead of a class, do.</p><p>However, when you need the lifecycle hooks or state, until React settles on some purely <a href="https://github.com/reactjs/react-future/tree/master/07%20-%20Returning%20State">functional</a> <a href="https://github.com/reactjs/react-future/tree/master/09%20-%20Reduce%20State">solution</a>, I see no harm in using classes given that you don’t break the rules above. <em>In fact</em> <em>it will be</em> <em>easier to migrate from ES6 classes to a purely functional approach than from anything else.</em></p><p>I am thus concerned about using “compositional solutions” that don’t directly harness React’s composition model, as in my view it’s a step back and conceptually is closer to mixins that don’t make sense in the functional paradigm.</p><p>So what are my recommendations for React components?</p><ul><li>You can use <em>class </em>in your JS if you don’t inherit twice and don’t use <em>super</em>.</li><li>Prefer to write React components as pure functions when possible.</li><li>Use ES6 classes for components if you need the state or lifecycle hooks.</li><li>In this case, you may only extend <em>React.Component</em> directly<em>.</em></li><li>Give your feedback to the React team on the functional <a href="https://github.com/reactjs/react-future/tree/master/07%20-%20Returning%20State">state</a> <a href="https://github.com/reactjs/react-future/tree/master/09%20-%20Reduce%20State">proposals</a>.</li></ul><p>Sleep well!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9af8de78ccb4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Inspiration]]></title>
            <link>https://medium.com/@dan_abramov/my-inspiration-ce454ab65f33?source=rss-a3a8af6addc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce454ab65f33</guid>
            <category><![CDATA[reacteurope]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Dan Abramov]]></dc:creator>
            <pubDate>Thu, 02 Jul 2015 19:41:28 GMT</pubDate>
            <atom:updated>2015-07-02T19:41:28.937Z</atom:updated>
            <content:encoded><![CDATA[<p>Today I gave a talk on React Hot Loader, Redux, and the powerful developer tools that Redux makes possible. If you haven’t seen my talk yet, wait for the video — I’m sure it’ll be up soon!</p><p>In an earlier version of the slides, I had an “Inspiration” slide. I cut it, like I cut many other slides, to fit into the 30 minutes cap. If you were inspired by my talk, you probably already saw these three talks.</p><p>But if for some reason you missed either of them, I envy you.<br>They are the best.</p><ul><li><a href="https://www.youtube.com/watch?v=fU9hR3kiOK0">Turning the Database Inside Out</a></li><li><a href="https://vimeo.com/36579366">Inventing on Principle</a></li><li><a href="https://www.youtube.com/watch?v=j-kj2qwJa_E">Developing ClojureScript with Figwheel</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce454ab65f33" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Evolution of Flux Frameworks]]></title>
            <link>https://medium.com/@dan_abramov/the-evolution-of-flux-frameworks-6c16ad26bb31?source=rss-a3a8af6addc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c16ad26bb31</guid>
            <category><![CDATA[flux]]></category>
            <category><![CDATA[facebook]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Dan Abramov]]></dc:creator>
            <pubDate>Sat, 30 May 2015 21:54:24 GMT</pubDate>
            <atom:updated>2015-07-14T19:27:47.014Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*-EWCLp3L61waWLPTOH9Rkg.png" /></figure><p>There has been no shortage of great Flux implementations, such as <a href="https://github.com/acdlite/flummox">Flummox</a>, <a href="https://github.com/goatslacker/alt">Alt</a>, or <a href="http://fluxible.io/">Fluxible</a>. Most of them are focused on making Flux easier to use with the server rendering and reducing the boilerplate. They also often provide convenience utilities like <a href="https://medium.com/@dan_abramov/mixins-are-dead-long-live-higher-order-components-94a0d2f9e750">higher-order components</a> and asynchronous action helpers. Still, under the hood, many of them are built on top of the original <a href="https://facebook.github.io/flux/docs/dispatcher.html">Flux Dispatcher</a>.</p><p><strong>Reducing the boilerplate of Flux is often a tradeoff.</strong> Some libraries have chosen to forfeit the great properties of Flux in order to be more succinct.</p><p>Say, if the actions aren’t plain objects flowing through a central dispatcher, it is much harder to <a href="https://medium.com/@nextminds/replaying-bugs-with-flux-52f6bd8c8307">record and replay actions</a> for debugging. If the action type constants are not explicitly specified, and instead are generated from the method names, they might be more difficult to use together with the static analysis tools like <a href="http://flowtype.org/">Flow</a>. That there is no single Flux library is a good thing, as the acceptable tradeoffs may vary for every team.</p><p>Now, unless you’re light years ahead of us and working on <a href="https://github.com/omcljs/om/tree/next">Om Next</a>, <a href="https://facebook.github.io/react/blog/2015/02/20/introducing-relay-and-graphql.html">Relay</a> or something <a href="https://github.com/staltz/cycle">truly reactive</a>, you might actually enjoy using Flux in your applications. If this is the case, you might want to know if there’s any real evolution happening in the Flux world.</p><p>Sure, figuring out how to make the isomorphic Flux easy was a step forward, but after that, the changes I have seen were either too cosmetic, or too drastic to call it Flux. <strong>The unidirectional data flow is important, but so is the relative ease of use of Flux, even for people who are not very keen on the functional programming yet.</strong> I think that if something requires you to understand cursors or observables, it might be great, but it’s not Flux. (I <em>do</em> like observables. But that’s not my point.)</p><p>So is Flux evolving? For the first time in many months, I think that the answer is <em>yes</em>. There are two API changes that I have noticed consistently in many new Flux implementations. These changes complement each other, and while they seem cosmetic, they also open up some exciting possibilities that weren’t available before. And they don’t even introduce any new concepts, such as cursors or observables!</p><p>I’m sure that Facebook considered these ideas, but decided to focus on the data flow and the ease of initial understanding. However I think that we’ve lived with this simple Flux long enough that we know its downsides, and it’s time to make it right.</p><p>The first change is to have the action creators <em>return</em> the dispatched action.<br>What looked like this:</p><pre><strong>export function</strong> addTodo(text) {<br>  AppDispatcher.dispatch({<br>    type: ActionTypes.ADD_TODO,<br>    text: text<br>  });<br>}</pre><p>can look like this instead:</p><pre><strong>export function</strong> addTodo(text) {<br>  return {<br>    type: ActionTypes.ADD_TODO,<br>    text: text<br>  };<br>}</pre><p>Of course, we can no longer call the action creators directly, but if you want to support server rendering, you’re likely to wrap them anyway (or have the library do it for you) so they’re bound to a specific dispatcher instance.</p><p>Why is it beneficial? It decouples actions from the dispatcher. The dispatcher becomes an implementation detail. It inverts the control, and we’ll see why inverting the control in Flux is important very soon.</p><p>How can async action creators work with this pattern? We could let the user return a function for dispatching multiple actions over time.</p><pre><strong>export function</strong> addTodo(text) {<br>  <strong>return</strong> dispatch =&gt; ({<br>    dispatch({<br>      type: ActionTypes.ADD_TODO,<br>      text: text<br>    });</pre><pre>    API.addTodo(text).then(<br>      () =&gt; dispatch({<br>        type: ActionTypes.ADD_TODO_SUCCESS,<br>        text: text<br>      }),<br>      () =&gt; dispatch({<br>        type: ActionTypes.ADD_TODO_FAILURE,<br>        text: text<br>      })<br>    );<br>  });<br>}</pre><p>It’s easy to provide convenience helpers to make this pattern work with <em>Promise</em> or <em>Observable </em>without the boilerplate above.</p><p>This change is not so important by itself, but it works great in tandem with another change: <strong>making the Stores stateless.</strong> This sounds ridiculous, doesn’t it? Isn’t holding the state the point of Stores?</p><p>In my experience, it isn’t! Every Store I ever wrote was <em>managing</em> the state but there’s no reason for the Store to own the state. (Om users, please don’t roll your eyes now. If it’s obvious to you, you may as well go read LtU ;-)</p><p>What looked like this:</p><pre><strong>let</strong> _todos = [];</pre><pre><strong>const</strong> TodoStore = Object.assign(<strong>new</strong> EventEmitter(), {<br>  getTodos() {<br>    return _todos;<br>  }<br>});</pre><pre>AppDispatcher.register(<strong>function</strong> (action) {<br>  <strong>switch</strong> (action.type) {<br>  <strong>case</strong> ActionTypes.ADD_TODO:<br>    _todos = _todos.concat([action.text]);<br>    TodoStore.emitChange();<br>    <strong>break</strong>;<br>  }<br>});</pre><pre><strong>export default</strong> TodoStore;</pre><p>can look like this instead:</p><pre><strong>const </strong>initialState = { todos: [] };</pre><pre><strong>export default function </strong>TodoStore(state = initialState, action) {<br>  <strong>switch</strong> (action.type) {<br>  <strong>case</strong> ActionTypes.ADD_TODO:<br>    <strong>return</strong> { todos: state.todos.concat([action.text]) };<br>  <strong>default</strong>:<br>    <strong>return</strong> state;<br>}</pre><p>That’s what your Store really is: a function telling the initial state and how the subsequent actions transform it. There is no reason for the Store to actually <em>own</em> that state. It might be held in a single big tree, for example, but it would be an <em>implementation detail </em>of the dispatcher. You don’t have to use the cursors. You can keep the “stores” and “subscriptions” mentality if that’s what you like, because it is easy to understand and feels natural to use.</p><p>What do these changes buy us? Turns out, quite a few things:</p><ul><li>Stores and actions are just pure functions. They are <strong>easily testable in isolation.</strong></li><li>Hot reloading. It’s easy to set up true hot reloading for stateless functions, and I’m working on an <a href="https://github.com/gaearon/redux">experimental project</a> showing how <a href="http://youtube.com/watch?v=xsSnOQynTHs"><strong>both Flux Stores and Action Creators can be hot reloaded without disrupting the application development flow</strong></a>.</li><li>Easy transactions. The dispatcher owns the state and <strong>has the power to revert the application to any previous state</strong> without the programmer implementing something like <em>serialize()</em> or <em>deserialize()</em>. This, combined with hot reloading, enables <a href="https://github.com/gaearon/redux-devtools">very powerful developer tools</a>.</li><li>No need for <em>waitFor()</em> because <strong>the</strong> <strong>dispatcher controls emitting changes </strong>and can emit them after all the Store callbacks have run.</li><li>You can subscribe to the changes at the store level, but <strong>the dispatcher may also expose cursor-like functionality</strong> for the advanced users who need finer-grained updates.</li><li>You’re specifying <strong><em>what</em>, not <em>how</em></strong>. Just like in React.</li></ul><p>There are already quite a few work-in-progress experimental Flux frameworks exploring this (or similar) way of doing things. Here’s a few off the top of my head:</p><ul><li><a href="https://github.com/vigetlabs/microcosm">microcosm</a></li><li><a href="https://github.com/rpominov/fluce">fluce</a></li><li><a href="https://github.com/optimizely/nuclear-js">NuclearJS</a></li><li><a href="https://github.com/threepointone/disto">disto</a></li><li><a href="https://github.com/goatslacker/microflux">microflux</a></li><li><a href="https://github.com/glenjamin/fluctuations">fluctuations</a></li><li>and the one I just started working on, <a href="http://github.com/gaearon/redux">redux</a></li></ul><p>Keep this pattern in mind. You’ll see interesting things created with it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c16ad26bb31" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Death of React Hot Loader]]></title>
            <link>https://medium.com/@dan_abramov/the-death-of-react-hot-loader-765fa791d7c4?source=rss-a3a8af6addc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/765fa791d7c4</guid>
            <dc:creator><![CDATA[Dan Abramov]]></dc:creator>
            <pubDate>Tue, 21 Apr 2015 23:45:19 GMT</pubDate>
            <atom:updated>2015-09-03T02:28:03.683Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DDSIhOm12eZiR1ldSEoKmQ.png" /></figure><blockquote><strong>Update</strong></blockquote><blockquote>The ideas from this post have now materialized in <a href="https://github.com/gaearon/babel-plugin-react-transform/">babel-plugin-react-transform</a> and its ecosystem. Check out <a href="https://github.com/gaearon/react-transform-boilerplate">react-transform-boilerplate</a>!</blockquote><p><a href="http://gaearon.github.io/react-hot-loader/">React Hot Loader</a> is my first JavaScript open-source project. It has enjoyed a tremendous response, and it has changed my professional life. True functional programmers don’t take it seriously, but comparing the wonder I felt the first time it worked to the mundane reality of hot reloading today, I know that it has made a difference in people’s minds, workflows and expectations.</p><p>New projects sharing the same vision, such as <a href="http://amokjs.com/">Amok</a> by <a href="https://github.com/caspervonb">Casper Beyer</a> and <a href="https://github.com/milankinen/livereactload">LiveReactload</a> by <a href="https://github.com/milankinen">Matti Lankinen</a>, have appeared. <a href="https://github.com/BenoitZugmeyer">Benoît Zugmeyer</a> uses the core of React Hot Loader <a href="https://github.com/gaearon/react-hot-api/pull/9#issuecomment-77945087">inside an atom-shell application</a>. Just a few days ago <a href="https://github.com/mjohnston">Michael Johnston</a> of the <a href="https://github.com/Flipboard/react-canvas">react-canvas</a> fame managed to get React Hot Loader to work with React Native using <a href="https://github.com/mjohnston/react-native-webpack-server/">react-native-webpack-server</a>. I never expected any of this to happen, and I am thrilled and humbled to be in this company. Hell, I’m even going to <a href="https://github.com/react-europe/cfp-2015/pull/7">ReactEurope</a>!</p><p>The enthusiasm and the support I have received have been overwhelming. The flip side of this is that I’m always being <a href="https://medium.com/@codepo8/i-feel-like-a-fraud-and-thats-a-good-thing-cc1fa338b902">painfully aware</a> that React Hot Loader is a great <em>hack</em>. It’s not how hot reloading <em>should</em> work. What it shows is that it <em>can </em>work given today’s JavaScript applications’ constraints, despite the mutability, despite the state, and despite a myriad of other sins we commit in our apps.</p><p>In the long term, we should <em>bring the better hot reloading solutions to the mainstream</em> by spreading ideas, raising money for such projects, building tools, and documenting great, but obscure technologies that deserve to be widely adopted. I’ll be thrilled to deprecate React Hot Loader when I see a better way of achieving the same developer experience in JavaScript.</p><p>However, in the short term, there’s still a few things I want to fix in React Hot Loader before sending it off to gather dust in the legacy treasury of in-house IT departments.</p><p><strong>Here’s how I think React Hot Loader 2 should be different.</strong></p><ul><li>Instead of the <a href="https://github.com/gaearon/react-hot-loader/tree/master/docs#you-can-make-hot-anything-else-via-opt-in-modulemakehot-api">weird <em>module.makeHot</em> opt-in API</a>, <strong>export a </strong><a href="https://github.com/wycats/javascript-decorators"><strong>decorator</strong></a><strong>.</strong> Marking a class for hot reloading should be as easy as putting <em>@hotify</em> on it. In production, it would compile to a no-op, so there is no need for conditional statements in the user code. <strong>The project exporting <em>@hotify</em> decorator should be independent of Webpack. (<em>Update: </em></strong><a href="https://github.com/gaearon/react-hotify"><strong><em>its alpha version is now available</em></strong></a><strong><em>!</em>)</strong> Re-evaluating the entire script with the new code with <em>@hotify</em> decorators in both scripts should have the same effect as hot reloading, except that such re-evaluation would usually cause unwanted side effects. (Which is where Webpack’s <a href="https://github.com/webpack/docs/wiki/hot-module-replacement-with-webpack">Hot Module Replacement</a> fits nicely, providing granular bubbling module updates and module cache for the unchanged modules.)</li><li>Hotifying only module exports doesn’t cut it anymore. It doesn’t work with <a href="https://medium.com/@dan_abramov/mixins-are-dead-long-live-higher-order-components-94a0d2f9e750">higher-order components</a> that wrap the real classes. Instead, we need to go back to <strong>finding React components in the source code</strong>. It was tricky and unreliable when React Hot Loader operated on the source file string, but <strong>what if it was a </strong><a href="https://babeljs.io/docs/usage/plugins/"><strong>Babel plugin</strong></a><strong> instead? (<em>Update: </em></strong><a href="https://github.com/gaearon/babel-plugin-react-hotify/blob/master/index.js"><strong><em>its alpha version is now available too</em></strong></a><strong><em>!</em>)</strong> For example, a plugin could slap <em>@hotify</em> onto any class with <em>render</em> method. It could also be configured to process module exports and even locate components using a custom project-wide heuristic. That Babel plugin could even generate hot reloading code for Webpack (and potentially, other build systems).<strong> </strong>This way we may be able to converge with <a href="https://github.com/milankinen/livereactload">LiveReactload</a> at some point.</li><li>What about the CoffeeScript and other compile-to-JS users? <strong>Nothing prevents them from keeping using the old Webpack loader!</strong> It would just need to be changed to hotify exports using the same <em>@hotify</em> decorator that the Babel plugin would use.</li></ul><p>We already have a separate <a href="https://github.com/gaearon/react-hot-api">“hot loader core”</a> project, but its API is not usable directly and, frankly, hard to understand. In the coming months, I will work on making it more developer-friendly.</p><p>As the time passes, React Hot Loader will gradually disappear. Instead, I hope that an ecosystem will appear, each part ready to be replaced by something better when the time is right.</p><p><a href="http://twitter.com/dan_abramov">Follow Dan Abramov on Twitter</a></p><p>⚛</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=765fa791d7c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>