<?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[Capbase Engineering - Medium]]></title>
        <description><![CDATA[Tales from the Engineering Team that helps other startups start up! - Medium]]></description>
        <link>https://medium.com/capbase-engineering?source=rss----42a54d5bb6ee---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Capbase Engineering - Medium</title>
            <link>https://medium.com/capbase-engineering?source=rss----42a54d5bb6ee---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 18:55:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/capbase-engineering" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[React Hooks for GraphQL Queries & Mutations]]></title>
            <link>https://medium.com/capbase-engineering/react-hooks-for-graphql-queries-mutations-f65274a38175?source=rss----42a54d5bb6ee---4</link>
            <guid isPermaLink="false">https://medium.com/p/f65274a38175</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-amplify]]></category>
            <category><![CDATA[aws-appsync]]></category>
            <dc:creator><![CDATA[Stefan Nagey]]></dc:creator>
            <pubDate>Mon, 14 Jan 2019 18:55:31 GMT</pubDate>
            <atom:updated>2019-01-14T18:55:31.522Z</atom:updated>
            <content:encoded><![CDATA[<h3>React Hooks for GraphQL Queries</h3><p>In this article, I’m going to show you how to create hooks to make working with graphQL a complete piece of cake!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nzVtxGKC2oHokoUfL3fmRQ.png" /><figcaption>Using React Hooks to tame GraphQL with AWS Amplify</figcaption></figure><p>If you’ve been following our journey with functional programming in Javascript with React, you’ll be all set, but if not, check out the beginning of our series for <a href="https://medium.com/capbase-engineering/react-hooks-is-the-functional-paradise-youve-been-waiting-for-994e53f65f94">functional programming with react hooks</a>.</p><p>The usage and concepts of GraphQL itself is beyond the scope of this article, and OPENGraphQL has a phenomenal set of resources <a href="https://medium.com/open-graphql/tagged/aws-appsync">in their publication</a> that deal with GraphQL, Apollo, Prisma, Hasura, and AWS AppSync (the library that we’re using here at <a href="https://capbase.com/">Capbase</a>).</p><p>The combination of functional components, hooks, and GraphQL can make working with data from a GraphQL Backend source as simple as including information from a local file.</p><h4>Why bother writing a hook?</h4><p>If we write a hook to handle our queries, and manage their asynchronous nature, we can have our display code be much more straightforward, same as if we were getting our results passed in as props to the component.</p><p>Let’s take a look at how that’s going to look.</p><h4>Using our Hook / A Sneak Peek at the Finished Product</h4><p>When we’re done with our hook, it’ll look something like this when we want to go use it.</p><pre>import GenericLoader from &quot;componets/GenericLoader&quot;;<br>import { searchStarWarsFilms } from &quot;graphql/queries&quot;;<br>import useGraphQuery from &quot;useGraphQuery.js&quot;;<br><br>const MyDisplayComponent = () =&gt; {<br>  const result = useGraphQuery(searchStarWarsFilms, {<br>    filter: { episode: { eq: &quot;IV&quot; } },<br>  });<br>  <br>  const film = result &amp;&amp; result.items &amp;&amp; result.items[0];<br><br>  return (film) ? (<br>      &lt;dl&gt;<br>          &lt;dt&gt;Episode&lt;/dt&gt;<br>          &lt;dd&gt;{film.episode}&lt;/dd&gt;<br>          &lt;dt&gt;Title&lt;/dt&gt;<br>          &lt;dd&gt;{film.title}&lt;/dd&gt;<br>          &lt;dt&gt;Characters&lt;/dt&gt;<br>          &lt;dd&gt;<br>            &lt;ul&gt;<br>              {film.characters.map( character =&gt; (<br>                  &lt;li key={character.id}&gt;<br>                    {character.name} portrayed by {character.actor}<br>                  &lt;/li&gt;<br>                ))}<br>            &lt;/ul&gt;<br>          &lt;/dd&gt;<br>      &lt;/dl&gt;<br>  ) : &lt;GenericLoader /&gt;;<br>};</pre><p>While this example is pretty straightforward, let’s walk through it.</p><h4>Using Amplify &amp; AppSync to turn GraphQL schemae into AWS Resources</h4><p>Let’s say that I’ve described an AppSync model along these lines (via AWS Amplify): ``` type StarWarsFilm @model @searchable { id: ID! Episode: String! Title: String! characters: [Character] @connection(name: “characters”) }</p><p>type FilmCharacter @model @searchable { id: ID! AppearsIn: StarWarsFilm! @connection(name: “characters”) Name: String Actor: String SalaryForFilm: Number } ```</p><p>This will auto-generate for me, the following resources: * Two DynamoDB tables, one named StarWarsFilms and another named FilmCharacters * An ElasticSearch instance * A lambda to stream data from the DynamoDB table into the ElasticSearch instance</p><p>Amplify will also create for me the following useful Javascript variables (as strings that describe GraphQL operations): * Queries to list all of each model * Queries to get an individual model * Queries to search by an attribute of a model * Mutations for CRUD</p><p>As always, you can define your own query and mutation strings for specific attributes that you want to get, but you get a whole bunch nicely auto-generated for you.</p><h4>Walking through the example usage of the finished hook</h4><p>OK, going back to the example, my first three lines are importing first a generic loader, then the auto-generated query string to search for a Star Wars Movie, and finally the hook that we’re going to create in the next section.</p><p>Then we define our functional component, and then I assign a value to the result of our hook.</p><p>The arguments for the hook are first the query that you want to use, and second, any parameters that you want to pass into the query. If we are searching or getting a model, then we need to pass in either a filter for the search, or the ID that we want to get.</p><p>Given the functional nature of what we do, when the value of the hook changes (that is, when we get our reply from the server) our component will re-execute and then that value will be available.</p><p>This can be seen from our return. Before we get our return from the GraphQL server, the value will be undefined. After we get it, this value with be a Javascript object, with a property named items which will contain a list of all the items which match our search. Since I know that in our dataset, searching for episode &quot;IV&quot; will give us a single response, I&#39;m gonna be a cowboy and just display the first result of the filter.</p><p>This first item in the list will be an object that describes our movie, and which contains a list of the characters in that movie.</p><p>From there, we’re just displaying these data in a dictionary list, but you can choose to use them anyway you like.</p><h4>Writing the hook useGraphQuery hook</h4><p>Our hook is going to do three things. 1. Use underlying React hooks to manage state and effects 2. Interact with the underlying GraphQL API, we’re using the AppSync api, you can also use Apollo, or the library of your choice 3. Handle our inputs and outputs in a developer-friendly way that is useful to our downstream devs</p><h4>The code for the useGraphQuery hook</h4><p>OK, let’s have a look at the raw code, then we’ll go through it line-by-line</p><pre>import { useEffect, useState } from &quot;react&quot;;<br>import { API, graphqlOperation } from &quot;aws-amplify&quot;;<br><br>export default (query, queryParams) =&gt; {<br>  const [queryResult, updateQueryResult] = useState(undefined);<br>    <br>  const runQuery = async () =&gt; {<br>    try {<br>      const queryData = await API.graphql(<br>        graphqlOperation(query, queryParams)<br>      );<br>      let queryName = query.match(/^query (.+)\((.*)/)[1];<br>      queryName = `${queryName[0].toLocaleLowerCase()}${queryName.substr(1)}`;<br>      updateQueryResult(queryData.data[queryName]);<br>    } catch (err) {<br>      // We wouldn&#39;t actually handle errors like this<br>      console.log(&quot;error: &quot;, err); <br>    }<br>  };<br><br>  useEffect(() =&gt; {<br>    runQuery();<br>  }, []);<br><br>  return queryResult;<br>};</pre><p>Alright, here’s what’s happening here.</p><p>Imports: the first two lines import the hooks that we’re going to use from React, in this case, useState and useEffect, and then the pieces of the Amplify library that we&#39;re going to use to interact with AppSync.</p><p>Our parameters into this function are, as mentioned earlier, are our query string, and then the parameters into that query string.</p><p>Now, what you’ll notice we do next is kind of interesting. We’re defining a piece of state to hold the result of our query. This means that we can later assign the result here and then the consumers of this hook will get re-called when this value updates. This piece of state is actually going to be the return value from our hook.</p><p>Next, we define the function that is going to handle the API interaction as an asynchronous function. If you look further down, you’ll see that that’s because we’re going to call this from the useEffect call.</p><p>We can’t have the useEffect callback itself be asynchronous, so we have to define it separately and then call it in there. You can check out my article on <a href="https://medium.com/capbase-engineering/asynchronous-functional-programming-using-react-hooks-e51a748e6869">async functional programming with javascript</a> for more on how this is working.</p><p>If we look at how our runQuery function works, we see that we&#39;re first preparing the query with the inner call to graphqlOperation which takes our query string, and the parameters thereto. That is then passed into the API call, which is asynchronous, and which we are await-ing here.</p><p>Next is just some syntactic sugar that we’re giving to our consumers. Since GraphQL is going to wrap the result of the query in an object whose member matches the name of the query, we’re just unwrapping that, and proving the result bare.</p><p>Then we’re going to update the result. This makes sure that the components consuming this hook are called again when this value changes. This is actually the magic that lets our downstream consumers use this so beautifully.</p><p>Lastly, we’re going to handle our errors, which we’re just logging to console here, but that hopefully you’ve got a better way to deal with.</p><p>Now we just call our function using useEffect — <em>note</em> if we wanted to make sure that the query were re-run when the parameters changed, then, instead of passing [] into useEffect, we would instead pass [queryParams].</p><p>Then we return the stateful value to our consumer, so that they can be updated when we get our result.</p><h4>Why bother with this?</h4><p>Since so much of what we do with async programming is boilerplate, it makes sense to extract as much of this boilerplate as we can, and also make it as easy to consumer these resources as possible in the future.</p><p>So here, we’ve reduced the complexity of interacting with a remote api, error handling, and async operations into a single call that lets our consumers treat our remote database just like a local synchronous function.</p><p>Pretty neat, eh?</p><h4>What’s next?</h4><p>Next time, we’ll look at how to do this same thing, but with mutations. In the future, I’ll show you how to create a hook for subscription as well.</p><p>I hope that this article has been useful to you. For more on how to work with react hooks and functional programming in javascript, check out <a href="https://medium.com/@stefann/part-2-using-react-hooks-to-manage-local-state-with-functional-components-3676fcd5646e">some</a> <a href="https://medium.com/@stefann/part-3-the-react-hooks-based-alternative-to-redux-and-the-flux-pattern-a726220a8a9a">of</a> <a href="https://medium.com/@stefann/react-hooks-is-the-functional-paradise-youve-been-waiting-for-994e53f65f94">the</a> <a href="https://medium.com/capbase-engineering/asynchronous-functional-programming-using-react-hooks-e51a748e6869">articles</a> <a href="https://medium.com/@stefann/gotchas-of-working-with-react-hooks-and-concurrent-mode-72157f5367eb">in the series.</a></p><p>Thanks, and please let me know any questions, comments, or complaints in the section below!</p><h4>About the Author</h4><p>Stefan Nagey is Co-Founder of <a href="https://capbase.com/">Capbase</a> and <a href="https://dharma.ai/">Dharma</a>. In a previous life he has variously promoted motion pictures, been a diplomat and registered foreign agent, and run payment processing in the online gambling space. He variously writes about engineering and the headaches of being a startup founder in the 21st century.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f65274a38175" width="1" height="1" alt=""><hr><p><a href="https://medium.com/capbase-engineering/react-hooks-for-graphql-queries-mutations-f65274a38175">React Hooks for GraphQL Queries &amp; Mutations</a> was originally published in <a href="https://medium.com/capbase-engineering">Capbase Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gotchas of working with React Hooks and Concurrent mode]]></title>
            <link>https://medium.com/capbase-engineering/gotchas-of-working-with-react-hooks-and-concurrent-mode-72157f5367eb?source=rss----42a54d5bb6ee---4</link>
            <guid isPermaLink="false">https://medium.com/p/72157f5367eb</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[programming-tips]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[gotchas]]></category>
            <dc:creator><![CDATA[Stefan Nagey]]></dc:creator>
            <pubDate>Sat, 12 Jan 2019 03:19:09 GMT</pubDate>
            <atom:updated>2019-01-12T03:19:09.048Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CiF-uDsstxpF-TU0lAsbzA.jpeg" /><figcaption>React Hooks make things better, but there are still Gotchas to React Hooks</figcaption></figure><p>While in this series, I’ve painted a very rosy picture of the functional world of react hooks, including part 1: <a href="https://medium.com/@stefann/react-hooks-is-the-functional-paradise-youve-been-waiting-for-994e53f65f94">why do we care about hooks in the first place; </a>part 2: <a href="https://medium.com/@stefann/part-2-using-react-hooks-to-manage-local-state-with-functional-components-3676fcd5646e">how to manage state in stateless components when working with react hooks</a>; part 3: <a href="https://medium.com/@stefann/part-3-the-react-hooks-based-alternative-to-redux-and-the-flux-pattern-a726220a8a9a">how to work with complex states and stores from redux with react hooks and stateless components</a>; and part 4: <a href="https://medium.com/@stefann/asynchronous-functional-programming-using-react-hooks-e51a748e6869">asynchronous functional programming with the useEffect hook</a>, it’s not always sun and roses when working with hooks. There are a few key issues and “gotchas” that you should be aware of in this paradigm, and this piece will explore those fully.</p><h3>Gotchas of Hooks, and How to avoid them</h3><p>As mentioned earlier in the series, when working with hooks, you have to be careful to use them only in the main function body.</p><p>Hooks cannot be used in any conditions, and can most certainly not be used in a loop.</p><p>The reason for this is to make sure that the hooks being used by a component can be statically analyzed and optimized. Hooks are also (relatively) expensive operations, so you don’t want to be storing millions of states when you could have just stored those same data in a single struct.</p><p>Luckily, there is <a href="https://www.npmjs.com/package/eslint-plugin-react-hooks">an eslint rule</a> that will help you keep track of this.</p><h3>React Concurrent Mode and Hooks: A Word of Caution</h3><p>While everything that we’ve discussed here can be seen to be mostly linear in nature. Once concurrent mode comes into play, this isn’t necessarily going to be the case. For example, you wouldn’t want to necessarily initialize a context in a component with items that are set from a higher up context.</p><p>That was confusing, let me explain.</p><p>Let’s say that you have a component that does a back end call, sets some data in a context, then redirects to another route.</p><p>In the non-concurrent world, each of these things would happen in order. First your dispatch would complete, then the &lt;Redirect /&gt; component would render. Then, in the component to which you have been redirected, you would have the result of the dispatch method available in the context on the first time the function is executed. As a result, you could use this as an initial state to open some internal context in that component.</p><p>With concurrency active, it will execute your component downstream of the Redirect as soon as Redirect is first called (i.e., React won’t wait for the Redirect component to render and for the dispatch to complete).</p><p>In almost all cases this won’t be a problem, <em>unless</em> as mentioned, you’re using this as a part of a state that wouldn’t necessarily be tracked the same way.</p><p>You can get around this by making sure to always use reducers in conjunction with your contexts, and to always set your initial arguments as undefined, or something else that will let you know it’s not quite ready.</p><h3>Another React Concurrent Mode Gotcha (as of today)</h3><p>Due to the way the concurrent mode is implemented (i.e., it’s safe for functional components, less so for object-based ones), it has the side effect of setting React Strict Mode.</p><p>I don’t want to say that “most” npm react packages are not Strict Mode safe, but, well, most npm react packages are not strict mode safe. We can hope that by the time that concurrent mode reaches release many of them well be (e.g., react-router currently has its next tag as strict mode compatible); one should not be confident that necessarily all packages will get there in time (looking at you react-intl from yahoo…). Even React.lazy has some unintended side effects when running in strict mode.</p><p>Concurrent mode can definitely make things feel snappier, but at this point, it’s probably safer to just stay way.</p><h3>Wrapping it all up with a nice bow</h3><p>React hooks present an amazing new set of functionality that allow React to be written in a completely functional manner, and open the door to all sorts of possibilities for performant (fast), efficient (low memory usage), and responsive (non-blocking / concurrent) web applications. We’ve looked at why functional programming in React is important; how you can manage state when writing stateless react components; how you can replace redux’s connect in a functional world; and how to handle asynchronous tasks when working with functional components.</p><p>I hope you enjoyed it, I’d love to hear what you think, and what I might’ve messed up.</p><h4>About the Author</h4><p>Stefan Nagey is Co-Founder of <a href="https://capbase.com/">Capbase</a> and <a href="https://dharma.ai/">Dharma</a>. In a previous life he has variously <a href="https://en.wikipedia.org/wiki/Sky_Captain_and_the_World_of_Tomorrow">promoted</a> <a href="https://www.imdb.com/title/tt0368008/">motion</a> <a href="https://www.rottentomatoes.com/m/paycheck/">pictures</a>, been a <a href="http://mexico.mx/">diplomat</a> and <a href="http://www.qorvis.com/">registered foreign agent</a>, and run payment processing in the <a href="https://www.fulltilt.com/">online gambling space</a>. He variously writes about engineering and the headaches of being a startup founder in the 21st century.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72157f5367eb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/capbase-engineering/gotchas-of-working-with-react-hooks-and-concurrent-mode-72157f5367eb">Gotchas of working with React Hooks and Concurrent mode</a> was originally published in <a href="https://medium.com/capbase-engineering">Capbase Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Asynchronous Functional Programming Using React Hooks]]></title>
            <link>https://medium.com/capbase-engineering/asynchronous-functional-programming-using-react-hooks-e51a748e6869?source=rss----42a54d5bb6ee---4</link>
            <guid isPermaLink="false">https://medium.com/p/e51a748e6869</guid>
            <category><![CDATA[async-functions]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Stefan Nagey]]></dc:creator>
            <pubDate>Sat, 12 Jan 2019 03:18:56 GMT</pubDate>
            <atom:updated>2019-01-12T03:18:55.916Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Nco5zYP_Xv-5-FgL6kCuw.png" /><figcaption>How to use async/await with stateless React components</figcaption></figure><p>In the first three parts of this series, we’ve looked at why <a href="https://medium.com/@stefann/react-hooks-is-the-functional-paradise-youve-been-waiting-for-994e53f65f94">functional programming is important to react</a>, how to <a href="https://medium.com/@stefann/part-2-using-react-hooks-to-manage-local-state-with-functional-components-3676fcd5646e">manage state in a stateless component</a>, and how to replace the flux pattern or <a href="https://medium.com/@stefann/part-3-the-react-hooks-based-alternative-to-redux-and-the-flux-pattern-a726220a8a9a">replace redux with React hooks</a>. In this part, we’re going to look at how to handle asynchronous tasks in the functional programming world, and how you can use the async/await pattern when working with React Hooks and stateless components.</p><h4>I simply have to wait for something — being async in a synchronous functional world</h4><p>As you’ve noticed, everything that we’ve talked about until now has been completely linear and synchronous. If we’re just working with a simple webpage, that’s all well and good, but what if we need to use a backend, what if we need to venture into the <em>asynchronous</em> world?</p><p>Luckily, useEffect is made for exactly that purpose.</p><p>The React.useEffect hook takes a function as an argument and it will call that function <em>after</em> the main render cycle has completed, meaning that you can use it to complete async operations, like calls to an API remote, whether it be GraphQL or RESTful (or SOAP or really whatever you like).</p><p>It’s generally best practice to define a function that you call from your effect and then do your async operations <em>there</em>. It allows you to use the async/await paradigm, which, I think we can all agree, makes life easier.</p><p>Let’s take a look at a simple async handler, we’ll call it updateProductBackend.</p><pre>const updateProductBackend = async (product) =&gt; {<br> return await updateBackend(product);<br>}</pre><p>This is very simple, it doesn’t update our UI or anything like that, however, since closures are a thing that exist, we can use any variable in the current scope (including, say, a update function pointer from a useState call or the dispatch method from a useContext call where the context provider was initialized with useReducer to do that for us. Or, if we don’t want to use closures, then we can pass those items into this handler and use them there, they’ll still work.</p><p>That might make this function look something like this:</p><pre>const updateProductBackend = async (product, dispatch) =&gt; {<br> const result = await updateBackend(product);<br> if (result.success) {<br>   dispatch({ type: “success” });<br> } else {<br>   dispatch({ type: “failure” });<br> }<br>}<br></pre><p>Of course, for this to be meaningful, our middleware reducer has to be extended to handle the success and failure action types.</p><h4>The React.useEffect call</h4><p>Let’s now take the async handler we defined in the previous section and put it to use inside a useEffect call.</p><p>In the body of any component, we can now add the following code:</p><pre>useEffect(() =&gt; updateProductBackend(product, dispatch));</pre><p>Let’s look at our ProductDisplay component from earlier, and see how this fits in.</p><pre>const ProductDisplay = () =&gt; {<br> const { <br>   state: product, <br>   dispatch <br> } = React.useContext(ProductsContext);<br> <br> useEffect(() =&gt; updateProductBackend(product, dispatch));<br> <br> return &lt;Product data={product} /&gt;;<br>};</pre><p>This is fine, but the eagle eyed reader will notice that this effect will call our backend every single time that our state changes. We probably don’t want that.</p><p>Let’s say that we’ve got a <a href="http://woot.com/">woot</a> like item that increments our price by a penny each time someone buys.</p><p>To do this, we’ll need a buy button, and then we’ll need to handle that price increment, but only if the product is bought.</p><p>Let’s accomplish this with a state that tells us if the user intends to purchase (we’ll call it purchaseIntent), and then an effect to do the purchase and to increment the price.</p><pre>const ProductDisplay = () =&gt; {<br> const { <br>   state: product, <br>   dispatch <br> } = React.useContext(ProductsContext);<br> <br> const [purchaseIntent, setPurchaseIntent] = useState(false);<br> <br> useEffect(() =&gt; {<br>   const newProduct = {<br>     …product, <br>     price: product.price + 0.01<br>   };<br>   if (purchaseIntent) {<br>     updateProductBackend(newProduct, dispatch);<br>     purchaseProduct(product, dispatch);<br>   }<br>   return null;<br>  },<br>  [ purchaseIntent ]<br> );<br> <br> return (<br>   &lt;React.Fragmemt&gt;<br>   &lt;Product data={product} /&gt;<br>   &lt;button onClick={() =&gt; setPurchaseIntent(true);} /&gt;<br> );<br>};</pre><p>What you should note here is the fact that I’ve passed purchaseIntent as the second argument to useEffect. What this does is to tell useEffect that it needs to execute the first argument if the value it receives in the second argument is different from the last value received. Given that before the first time, it’s undefined, it will run the first time as well (hence the check on purchaseIntent).</p><p>It’s also important here to note that if your call to useEffect has any long-running consequences, you need to return a callback that will terminate these processes.</p><h3>Wrapping it all up</h3><p>As you can see through these examples, hooks allow us to do absolutely everything that we would in the classic react lifecycle method, but everything is in a single flow, where we don’t have to worry about all the complexities that the object model exposed us to.</p><p>This allows each piece to become a more discrete unit (which, as such, can be unit tested), and to keep all of the pieces simple as well.</p><p>It also has the wonderful side effect of being faster. Since with this approach, your functions are not long-running and don’t contribute to the heap size like objects do, your app will have a lower overall memory footprint and run more smoothly everywhere it runs.</p><h3>Read More — Other parts in this series</h3><p>If you haven’t seen it, please also read part 1, discussing the reasons for functional programming and <a href="https://medium.com/@stefann/react-hooks-is-the-functional-paradise-youve-been-waiting-for-994e53f65f94">stateless components in react</a>, part 2 managing <a href="https://medium.com/@stefann/part-2-using-react-hooks-to-manage-local-state-with-functional-components-3676fcd5646e">local state with React Hooks</a>, and part 3 replacing your <a href="https://medium.com/@stefann/part-3-the-react-hooks-based-alternative-to-redux-and-the-flux-pattern-a726220a8a9a">redux action/reducer pattern with the react Hooks </a><a href="https://medium.com/@stefann/part-3-the-react-hooks-based-alternative-to-redux-and-the-flux-pattern-a726220a8a9a">useContext and </a><a href="https://medium.com/@stefann/part-3-the-react-hooks-based-alternative-to-redux-and-the-flux-pattern-a726220a8a9a">useReducer hooks</a>.</p><p>Coming up next will be the final part in this series, exploring the various <a href="https://medium.com/@stefann/gotchas-of-working-with-react-hooks-and-concurrent-mode-72157f5367eb">gotchas of working with React Hooks, React Concurrent Mode, and Functional Programming in Javascript</a>.</p><h4>About the Author</h4><p>Stefan Nagey is Co-Founder of <a href="https://capbase.com/">Capbase</a> and <a href="https://dharma.ai/">Dharma</a>. In a previous life he has variously <a href="https://en.wikipedia.org/wiki/Sky_Captain_and_the_World_of_Tomorrow">promoted</a> <a href="https://www.imdb.com/title/tt0368008/">motion</a> <a href="https://www.rottentomatoes.com/m/paycheck/">pictures</a>, been a <a href="http://mexico.mx/">diplomat</a> and <a href="http://www.qorvis.com/">registered foreign agent</a>, and run payment processing in the <a href="https://www.fulltilt.com/">online gambling space</a>. He variously writes about engineering and the headaches of being a startup founder in the 21st century.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e51a748e6869" width="1" height="1" alt=""><hr><p><a href="https://medium.com/capbase-engineering/asynchronous-functional-programming-using-react-hooks-e51a748e6869">Asynchronous Functional Programming Using React Hooks</a> was originally published in <a href="https://medium.com/capbase-engineering">Capbase Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 3: The React Hooks based alternative to Redux and the Flux pattern]]></title>
            <link>https://medium.com/capbase-engineering/part-3-the-react-hooks-based-alternative-to-redux-and-the-flux-pattern-a726220a8a9a?source=rss----42a54d5bb6ee---4</link>
            <guid isPermaLink="false">https://medium.com/p/a726220a8a9a</guid>
            <category><![CDATA[react-context]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[react-hook]]></category>
            <dc:creator><![CDATA[Stefan Nagey]]></dc:creator>
            <pubDate>Sat, 12 Jan 2019 03:18:42 GMT</pubDate>
            <atom:updated>2019-01-13T17:17:52.832Z</atom:updated>
            <content:encoded><![CDATA[<h3>The React Hooks based alternative to Redux and the Flux pattern</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6oeKSYnPG2pbg8vdaiteYg.png" /><figcaption>There is a better way than Redux. Hooks + Context FTW</figcaption></figure><p>In this article, we will be looking at how to implement Redux, Saga, Thunk, and Flux based thinking with the pure functional programming power that comes with React Hooks.</p><p>ICYMI, be sure to also check out <a href="https://medium.com/@stefann/react-hooks-is-the-functional-paradise-youve-been-waiting-for-994e53f65f94">Part 1: React Hooks is the functional paradise you’ve been waiting for</a> and <a href="https://medium.com/@stefann/part-2-using-react-hooks-to-manage-local-state-with-functional-components-3676fcd5646e">Part 2: Local State management using React Hooks</a>. Also be sure to check out the forthcoming <a href="https://medium.com/@stefann/asynchronous-functional-programming-using-react-hooks-e51a748e6869">Part 4: Asynchronous Functional Programming with React’s </a><a href="https://medium.com/@stefann/asynchronous-functional-programming-using-react-hooks-e51a748e6869">useEffect hook</a>, and <a href="https://medium.com/@stefann/gotchas-of-working-with-react-hooks-and-concurrent-mode-72157f5367eb">Part 5: Gotchas of working with React Hooks and React’s new Concurrent Mode.</a></p><h3>Handling large, complex, states easily with the useContext and useReducer hooks</h3><p>In the the previous parts, we’ve seen where we can easily handle states in a single component. Let’s look now at how we can approach this over multiple components.</p><p>Let’s say that we’ve got a list of products, and we want to render detailed data about them. Let’s imagine a markup that looks something like this:</p><pre><br>const ProductList = ({ products }) =&gt; products.map(<br>  product =&gt; &lt;Product data={product} /&gt;<br>);</pre><pre>const Product = ({ name, description, price }) =&gt; (<br> &lt;dl&gt;<br> &lt;dt&gt;Product Name:&lt;/dt&gt;<br> &lt;dd&gt;{name}&lt;/dd&gt;<br> &lt;dt&gt;Product Description:&lt;/dt&gt;<br> &lt;dd&gt;{description}&lt;/dd&gt;<br> &lt;dt&gt;Product Price:&lt;/dt&gt;<br> &lt;dd&gt;{price}&lt;/dd&gt;<br>);</pre><p>Now, this is pretty straight forward, we’re getting props from upstream, and we’re drilling them down.</p><p>Works fine, but it might be that we want to do more complex things, or we want to update the product state and have it propagate upward.</p><p>Let’s first put our state into a Context, called ProductsContext. First we create the context, easy, like this:</p><pre>const ProductsContext = React.createContext();</pre><p>A context is just a bucket that can store an object (again, think like a struct) in a property called value.</p><p>We could just shove our products variable in here, and that would work pretty well. Let’s see:</p><pre>const ProductContext = React.createContext();</pre><pre>const ProductList = ({ products }) =&gt; {</pre><pre>return products.map(product =&gt; (<br> &lt;ProductContext.Provider value={ {product} }&gt;<br> &lt;ProductDisplay /&gt;<br> &lt;/ProductContext.Provider&gt;<br> ));</pre><pre>const ProductDisplay = () =&gt; (<br> const { product } = React.useContext(ProductsContext);<br> return &lt;Product data={product} /&gt;<br>);</pre><p>This is pretty neat. It makes it so that we don’t have to drill the product list down, and also makes it so that we could easily have multiples of these at any level.</p><p>I could’ve also just used this context directly in the Product component (but I didn’t, just so that we don’t have to edit that one).</p><h4>Managing Context values with useReducer</h4><p>So, now the obvious question is, “how do we change the values in the context?” — for that, the React team has given us a great little tool, useReducer.</p><p>useReducer is just like useState in that you get back a value that stores your state, and a function pointer that can be used to update that state (just like dispatch in redux world. Where it differs is that not only does it take an initial value, but it also takes a second value for a middleware, or reducer (to borrow from the redux terminology).</p><p>This middleware function will receive both the current state, as well as the argument passed to the dispatcher, and is expected to return a new value for the state.</p><p>With this, we can now store both this state and this dispatch function in the value of the reducer, so that in any downstream component, we can modify the state by calling into the dispatch method.</p><p>Let’s look at an exceedingly simple method of modifying our ProductList, adding a product, and removing a product.</p><h4>A simple middleware</h4><p>Let’s have a look at a simple middleware that is just adding or removing a product from our context.</p><p>We’ll use the familiar redux convention of an action that as an object that has two properties, a type and a payload. The type is a way to communicate to the middleware reducer which action you want to take, and the payload is the data necessary to carry out that action.</p><p>In this example, I’ll split the method to reduce each type of action into its own function, but there’s no reason you can’t keep this all in the body of the reducer. I’ll show you one of each</p><p>Let’s look at the code:</p><pre>const middleware = (currentState, dispatchArgument) =&gt; {<br> switch(dispatchArgument.type) {<br> case ‘changeName’:<br> return changeProductName(currentState, dispatchArgument.payload);<br> case ‘changePrice’:<br> return { …state, price: dispatchArgument.payload } <br> };<br>};</pre><pre>const initialState = products;</pre><pre>const [state, dispatch] = React.useReducer(middleware, intialState);</pre><p>Now, if we want to change the price of a product, it can be as simple as this:</p><pre>dispatch({ type: ‘changePrice’, payload: 3.50 });</pre><p>This is great, but how do we get that to propagate down through the tree? Let’s look at how we hook this up to our context.</p><h4>Hooking useReducer together with useContext</h4><p>Here we’re going to change our previous call to ProductContext.Provider to take use the return values of our useReducer call from the previous section as its value. This will give us, in our context, both a value, and a way to change that value.</p><p>To make that easier, let’s make a method that wraps the previous code so that we can easily access it.</p><pre>const useProductReducer = (product) =&gt; {<br> const middleware = (currentState, dispatchArgument) =&gt; {<br>   switch(dispatchArgument.type) {<br>     case ‘changeName’:<br>      return changeProductName(<br>        currentState, dispatchArgument.payload<br>      );<br>     case ‘changePrice’:<br>      return { …state, price: dispatchArgument.payload };<br>   };<br> };</pre><pre>  const initialState = product;</pre><pre>  const [state, dispatch] = React.useReducer(<br>    middleware, intialState<br>  );<br> <br>  return { state, dispatch };<br>};</pre><p>OK, now we’ve create a simple function useProductReducer that will take a list of products, and will return a value we can use as the value for our context.</p><h4>Write your own hooks!</h4><p>The eagle eyed among you might notice that we call this use similar to the react hooks. That’s no accident. Congrats, you’ve just made your first hook!</p><p>A React hook is just any function that starts its name with use. Good hook hygiene requires you only call hooks from the function body (not within loops or conditionally), and that applies to hooks you create as well. Hooks you create are often most useful when they call other hooks, as we have here.</p><p>Now, let’s integrate our hook with the code for the context above:</p><pre>const ProductContext = React.createContext();</pre><pre>const ProductList = ({ products }) =&gt; {</pre><pre>return products.map(product =&gt; (<br> &lt;ProductContext.Provider value={useProductReducer(product)}&gt;<br>   &lt;ProductDisplay /&gt;<br> &lt;/ProductContext.Provider&gt;<br>));</pre><pre>const ProductDisplay = () =&gt; {<br> const { <br>   state: product, <br>   dispatch <br> } = React.useContext(ProductsContext);</pre><pre> return &lt;Product data={product} /&gt;<br>};</pre><p>You’ll notice here that we create a new context with its own reducer for each product, and then within that component, we can access the context and change the product.</p><p>Now, the way that we’re changing the product isn’t spectacularly interesting, but we can extend this example to modify a shopping cart, or to send items to a backend or some other remote.</p><h3>What comes next</h3><p>In this piece you’ve learned how you can use the useReducer and the useContext hooks to effortlessly manage huge state trees, and to move past the patterns of flux and redux into the functional, stateless world of react hooks.</p><p>In the next part of this series, we’ll look at working with remote and <a href="https://medium.com/@stefann/asynchronous-functional-programming-using-react-hooks-e51a748e6869">back-end systems using react hooks</a>, and how to manage asynchronous workloads with react hooks. Following that, the final part in this series will deal with the various <a href="https://medium.com/@stefann/gotchas-of-working-with-react-hooks-and-concurrent-mode-72157f5367eb">gotchas of working with React hooks.</a></p><p>If you missed it, please check out the first part of this series, in which we discuss the<a href="https://medium.com/@stefann/react-hooks-is-the-functional-paradise-youve-been-waiting-for-994e53f65f94"> importance of functional programming, and how stateless components can lead you to the promised land</a>, and part 2, where we discuss <a href="https://medium.com/@stefann/part-2-using-react-hooks-to-manage-local-state-with-functional-components-3676fcd5646e">how we can manage state in stateless components using the useState hook.</a></p><h4>About the Author</h4><p>Stefan Nagey is Co-Founder of <a href="https://capbase.com/">Capbase</a> and <a href="https://dharma.ai/">Dharma</a>. In a previous life he has variously <a href="https://en.wikipedia.org/wiki/Sky_Captain_and_the_World_of_Tomorrow">promoted</a> <a href="https://www.imdb.com/title/tt0368008/">motion</a> <a href="https://www.rottentomatoes.com/m/paycheck/">pictures</a>, been a <a href="http://mexico.mx/">diplomat</a> and <a href="http://www.qorvis.com/">registered foreign agent</a>, and run payment processing in the <a href="https://www.fulltilt.com/">online gambling space</a>. He variously writes about engineering and the headaches of being a startup founder in the 21st century.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a726220a8a9a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/capbase-engineering/part-3-the-react-hooks-based-alternative-to-redux-and-the-flux-pattern-a726220a8a9a">Part 3: The React Hooks based alternative to Redux and the Flux pattern</a> was originally published in <a href="https://medium.com/capbase-engineering">Capbase Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 2: Using React Hooks to manage local state with Functional Components]]></title>
            <link>https://medium.com/capbase-engineering/part-2-using-react-hooks-to-manage-local-state-with-functional-components-3676fcd5646e?source=rss----42a54d5bb6ee---4</link>
            <guid isPermaLink="false">https://medium.com/p/3676fcd5646e</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[state-management]]></category>
            <dc:creator><![CDATA[Stefan Nagey]]></dc:creator>
            <pubDate>Sat, 12 Jan 2019 03:18:26 GMT</pubDate>
            <atom:updated>2019-01-12T03:18:26.717Z</atom:updated>
            <content:encoded><![CDATA[<h3>Using React Hooks to manage local state with Functional Components</h3><p>In Part 1, we talked about the <a href="https://medium.com/@stefann/react-hooks-is-the-functional-paradise-youve-been-waiting-for-994e53f65f94">issues with the traditional class-based react </a>approach, and how functional programming can help alleviate some of that pain. In this part of my five part series, we’re going to look at how we can use the new React Hooks api (in the forthcoming React 16.8) to maintain a long-standing state while still living in the functional world of the so-called stateless components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Ijet6kVJqGgul6adezDLQ.png" /></figure><h3>Functions are great, but what about my persistent state?</h3><p>With the approach I’ve described in <a href="https://medium.com/@stefann/react-hooks-is-the-functional-paradise-youve-been-waiting-for-994e53f65f94">part 1</a>, it’s easy to see where some problems come in. What if I want to change my interface based on the user’s interaction with it? What if I want my interface to, y’know, *react*?</p><p>Let’s take a simple case. We have a page that has a button, and when you click the button, it changes the background color of the page. The base component for this might look something like this:</p><pre>const Page = () =&gt; {<br> const onColor = “#059ed8”;<br> const offColor = “#343a40”;<br> <br> const isItOn = true;<br> <br> const color = (isItOn) ? onColor : offColor;<br> <br> return (<br> &lt;div style={ color } &gt;<br> &lt;button /&gt;<br> &lt;/div&gt;<br> );<br>);</pre><p>OK, so, this is fine, but it doesn’t do what we want. How do we change the background?</p><p>In order to do that, we need to 1) keep track of the current state (on versus off), and 2) have the button change that state.</p><h4>How React Hooks solve functional problems — tracking state with useState</h4><p>In our first problem above, we need to keep track of the state.</p><p>What if I told you that I can give you a magic variable that you can change and it will instantly update everything.</p><p>Technically, I’ll give you a variable and a function to change it, but it’ll still be magic.</p><p>For our above example, I’ll in one line that lets you persist a state for our isItOn variable (setting its initial value to true as well).</p><pre>const [isItOn, …rest] = React.useState(true)</pre><p>Now, isItOn will be true, and will persist that. I’ve discarded the rest (we’ll get to that in a minute).</p><h4>Functional handlers for functional components</h4><p>Ok, so, now we have our state, but how do we use it / how do we modify it such that we can update our UI?</p><p>What comes into play now is the second variable that we had previously discarded, which we will now go into.</p><p>This second value is a function handle that we can pass in a new value to.</p><p>Let’s change our above code to the following:</p><pre>const [isItOn, setIsItOn] = React.useState(true)</pre><p>Now we can call setIsItOn(false) to change our state (or change it to any other value we like.</p><p>Let’s now create a simple toggle handler for the button that we have above.</p><pre>const toggleIsItOn = () =&gt; setIsItOn(!isItOn);</pre><p>This function will change that state value, and will (eventually) trigger another call of this function, where the value of the state variable has changed to this new value.</p><h4>Putting it together</h4><p>Ok, so now we’ve seen how the useState call can be used to bring us persistent state that can be used to track user interactions with our UI.</p><p>Let’s update our markup to include all the useState call and our button handler:</p><pre>const Page = () =&gt; {<br> const onColor = “#059ed8”;<br> const offColor = “#343a40”;<br> <br> const [isItOn, setIsItOn] = React.useState(true);<br> <br> const toggleIsItOn = () =&gt; setIsItOn(!isItOn);<br> <br> const color = (isItOn) ? onColor : offColor;<br> <br> return (<br> &lt;div style={ color } &gt;<br> &lt;button onClick={toggleIsItOn} /&gt;<br> &lt;/div&gt;<br> );<br>);</pre><p>Super simple, right?</p><p>Now, when this button is clicked, our toggleIsItOn function will be called, and this will trigger a re-render of our component, toggling our background color.</p><p>Of course, this doesn’t help us if we want to track state over multiple components, but that’s where contexts come in.</p><h3>Wrapping it all up</h3><p>As we’ve seen, React Hooks give us an easy way to handle state without having to rely on long-lived objects to store our classes, and how you can write functional components for React, the so-called stateless components, but still manage state.</p><p>In the next part, we’re going to look at larger, more complex states, and how you can completely replace your existing flux or redux action/reducer workflows with much simpler React Hooks workflows leveraging the `useReducer` hook.</p><p>If you’ve not seen it, please also check out <a href="https://medium.com/@stefann/react-hooks-is-the-functional-paradise-youve-been-waiting-for-994e53f65f94">Part 1: Problems with React’s Object-based model and Functional programming</a>, as well as the forthcoming parts 3, 4 and 5, <a href="https://medium.com/@stefann/part-3-the-react-hooks-based-alternative-to-redux-and-the-flux-pattern-a726220a8a9a">The React Hooks Alternative to the Redux and Flux Patterns</a>; <a href="https://medium.com/@stefann/asynchronous-functional-programming-using-react-hooks-e51a748e6869">Async Functional Programming using the useEffect Hook</a>; and<a href="https://medium.com/@stefann/gotchas-of-working-with-react-hooks-and-concurrent-mode-72157f5367eb"> Gotchas of working with React hooks</a>, respectively.</p><h4>About the Author</h4><p>Stefan Nagey is Co-Founder of <a href="https://capbase.com/">Capbase</a> and <a href="https://dharma.ai/">Dharma</a>. In a previous life he has variously <a href="https://en.wikipedia.org/wiki/Sky_Captain_and_the_World_of_Tomorrow">promoted</a> <a href="https://www.imdb.com/title/tt0368008/">motion</a> <a href="https://www.rottentomatoes.com/m/paycheck/">pictures</a>, been a <a href="http://mexico.mx/">diplomat</a> and <a href="http://www.qorvis.com/">registered foreign agent</a>, and run payment processing in the <a href="https://www.fulltilt.com/">online gambling space</a>. He variously writes about engineering and the headaches of being a startup founder in the 21st century.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3676fcd5646e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/capbase-engineering/part-2-using-react-hooks-to-manage-local-state-with-functional-components-3676fcd5646e">Part 2: Using React Hooks to manage local state with Functional Components</a> was originally published in <a href="https://medium.com/capbase-engineering">Capbase Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Hooks is the functional paradise you’ve been waiting for]]></title>
            <link>https://medium.com/capbase-engineering/react-hooks-is-the-functional-paradise-youve-been-waiting-for-994e53f65f94?source=rss----42a54d5bb6ee---4</link>
            <guid isPermaLink="false">https://medium.com/p/994e53f65f94</guid>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Stefan Nagey]]></dc:creator>
            <pubDate>Sat, 12 Jan 2019 03:13:05 GMT</pubDate>
            <atom:updated>2019-01-12T03:13:05.481Z</atom:updated>
            <content:encoded><![CDATA[<p>We’ve all been there before. A react app that gets so unwieldy and becomes an utter mess of tangled lifecycle component interactions such that you can’t tell up from down, right from wrong (or write from read?), black from white.</p><p>I’m here to tell you that there is another way.</p><p>There is salvation!</p><p>React hooks, it’s where it’s at.</p><p><strong>DISCLAIMER</strong> React hooks is still technically in alpha stage (16.8.0-alpha0 as of today, but that may change, use the `next` tag to be safe), so you shouldn’t use it for production, yada yada. That said, I am currently using it in a near production context, and apart from a brief misadventure with concurrent mode (more on that later) it is amazing.</p><p>I started off writing this as just a quick one-off. However, given that it’s now three thousand words later, I’m going to break this down into five parts, as follows:<br>1. The Basics: Problems in Class-based React and Functional Programming (this story)<br>2. <a href="https://medium.com/@stefann/part-2-using-react-hooks-to-manage-local-state-with-functional-components-3676fcd5646e">Local state management using react hooks</a><br>3. <a href="https://medium.com/@stefann/part-3-the-react-hooks-based-alternative-to-redux-and-the-flux-pattern-a726220a8a9a">Replacing Redux with React Hooks / Complex State Management with Hooks</a><br>4. <a href="https://medium.com/@stefann/asynchronous-functional-programming-using-react-hooks-e51a748e6869">Asynchronous Functional Programming &amp; hooks with effects</a><br>5. <a href="https://medium.com/@stefann/gotchas-of-working-with-react-hooks-and-concurrent-mode-72157f5367eb">Gotchas of Working with React Hooks &amp; the new Concurrent Mode</a></p><h3>The basics: Problems in Class-based React and their Functional Programming Solutions</h3><p>If you’ve been around the react world for a while, you’ve probably seen people talk about functional components, without thinking too much about what they are, beyond, “they’re supposed to be better.” However, like eating your vegetables, you might not have actually done it.</p><p>React’s lifecycle model can be quick and satisfying at first, but just like real world spaghetti, it will make you put on weight and lead to long-term problems.</p><p>In classic React, you would build each component as an object, and that component would get initialized with it’s constructor, and then you would get calls to methods like didComponentUpdate, willComponentUpdate, componentReceivedProps, render, and so on, and so forth.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y_Y5NPphMKA_ugd1Ll3ICg.png" /><figcaption>A relatively straightforward explanation of the spaghetti methods of classic react programming</figcaption></figure><p>Add on top of this something like redux where you have a global shared state that any component can connect to, access, and update (which will trigger a new round of updates), well, I’m sure you can see where you can start to run into some problems. All of these calls flying back and forth will very quickly turn into spaghetti, and can turn what should be a relatively straightforward debugging process turn into a mess of unintended behaviors, side effects, and consequences.</p><p>Functional programming in React can help to counteract all of that. Think of it as the Keto or Paleo alternative to the classic spaghetti model.</p><h4>What is functional programming?</h4><p>Functional programming (FP) in terms of React can be thought of very very simply. Everything is a function. No objects apart from Javascript objects, which you can — and should — treat like classic C structs. When you write a component, it’s a function. It receives arguments (as props), and it returns JSX.</p><p>When you write a functional component, your code runs straight through, one statement to the next. Race conditions are rare, and you can keep your code small and easy to understand.</p><p>There are no lifecycle methods to worry about, no complex internal state (because there is no state that persists from one run of the function to the next).</p><p>It drastically reduces the complexity of your code.</p><p>Now, I can hear some of you crying that it’ll make life harder if you can’t track state, and you can’t do things asynchronously, and, well, that’s where hooks come in. More on that later.</p><h3>Writing Functional React</h3><p>When you write functional react, all of your components are plain functions. They will receive their props as an argument, and they must return JSX.</p><p>The base of your component is your JSX, not much different than HTML. If the component gets too big, you can split it into smaller components, it’s as easy as:</p><pre>const MyNewComponent = () =&gt; (<br> &lt;div&gt;<br> &lt;p&gt; some markup &lt;/p&gt;<br> &lt;/div&gt;<br>);</pre><p>and then you can just call place that &lt;MyNewComponent /&gt; anywhere in your code you like (provided that it’s defined in your scope).</p><p>This also makes your code easier to test — simple inputs, simple outputs.</p><h4>Putting it to use and moving on</h4><p>In this part, you’ve seen why functional programming is important and what some of the Anti-patterns of writing React code using the traditional class-based approach are, and how functional, stateless components can help you overcome this.</p><p>In the upcoming parts of this series, we’ll take a look at<a href="https://medium.com/@stefann/part-2-using-react-hooks-to-manage-local-state-with-functional-components-3676fcd5646e"> how you can use state in a stateless component</a>; how we can <a href="https://medium.com/@stefann/part-3-the-react-hooks-based-alternative-to-redux-and-the-flux-pattern-a726220a8a9a">use react’s </a><a href="https://medium.com/@stefann/part-3-the-react-hooks-based-alternative-to-redux-and-the-flux-pattern-a726220a8a9a">useContext and </a><a href="https://medium.com/@stefann/part-3-the-react-hooks-based-alternative-to-redux-and-the-flux-pattern-a726220a8a9a">useReducer hooks to manage a complex state tree to replace flux, redux, and the connect/dispatch pattern </a>thereof; <a href="https://medium.com/@stefann/asynchronous-functional-programming-using-react-hooks-e51a748e6869">working with async tasks and using async/await with react hooks and the useEffect hook</a>; and finally <a href="https://medium.com/@stefann/gotchas-of-working-with-react-hooks-and-concurrent-mode-72157f5367eb">the gotchas of working with React hooks and functional react</a>.</p><h4>About the Author</h4><p>Stefan Nagey is Co-Founder of <a href="https://capbase.com/">Capbase</a> and <a href="https://dharma.ai/">Dharma</a>. In a previous life he has variously <a href="https://en.wikipedia.org/wiki/Sky_Captain_and_the_World_of_Tomorrow">promoted</a> <a href="https://www.imdb.com/title/tt0368008/">motion</a> <a href="https://www.rottentomatoes.com/m/paycheck/">pictures</a>, been a <a href="http://mexico.mx/">diplomat</a> and <a href="http://www.qorvis.com/">registered foreign agent</a>, and run payment processing in the <a href="https://www.fulltilt.com/">online gambling space</a>. He variously writes about engineering and the headaches of being a startup founder in the 21st century.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=994e53f65f94" width="1" height="1" alt=""><hr><p><a href="https://medium.com/capbase-engineering/react-hooks-is-the-functional-paradise-youve-been-waiting-for-994e53f65f94">React Hooks is the functional paradise you’ve been waiting for</a> was originally published in <a href="https://medium.com/capbase-engineering">Capbase Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>