<?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 Ian Huntington on Medium]]></title>
        <description><![CDATA[Stories by Ian Huntington on Medium]]></description>
        <link>https://medium.com/@ihuntington?source=rss-9f6505a5ed69------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*cZIcj3BiuDHXel_sfdSLzw.jpeg</url>
            <title>Stories by Ian Huntington on Medium</title>
            <link>https://medium.com/@ihuntington?source=rss-9f6505a5ed69------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 21:17:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ihuntington/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[A look into React state management in 2021]]></title>
            <link>https://medium.com/plumguide/a-look-into-react-state-management-in-2021-5fc46a247e65?source=rss-9f6505a5ed69------2</link>
            <guid isPermaLink="false">https://medium.com/p/5fc46a247e65</guid>
            <dc:creator><![CDATA[Ian Huntington]]></dc:creator>
            <pubDate>Fri, 16 Jul 2021 07:02:35 GMT</pubDate>
            <atom:updated>2021-07-21T08:16:55.049Z</atom:updated>
            <content:encoded><![CDATA[<p>At Plum Guide we have been primarily using React’s Context and useState to manage state within apps. This has worked well so far, for example on the listing pages, where state is shared in multiple branches of the React tree and there are a number of interactive components.</p><p>With some forthcoming projects that include search and host dashboard, I had the opportunity to investigate other state management libraries to see what other alternatives there are.</p><p>Our current approach to building with React is to start with either <a href="https://nextjs.org/">Next.js</a> or <a href="https://create-react-app.dev/">Create React App</a> depending on a projects particular set of requirements, such as whether server-side rendering is needed. Our frontend architecture consists of multiple micro-frontends and code is shared between these by a variety of internal libraries, including a component library.</p><h3>Best practices with React Context</h3><p>Over time as projects grow in terms of feature set and complexity, the amount of state that is contained also grows. To keep the complexity manageable we’ve adopted some best practices that have worked well for us when using the Context API:</p><ul><li>Keep state local until it needs to be shared with a common ancestor, if a sibling component depends on the state then lift it to their parent and pass it down to the components as a prop.</li><li>If a piece of state is required by multiple branches of the component tree (global state) then its a good time to introduce a provider.</li><li>Rather than store all state within one Context, separate state out into logical pieces. You may also find that not all providers need to be at the top of the React tree wrapping your entire app either. Use them where they are needed.</li><li>By using functional components React can make optimisations such as comparing props to determine whether a component needs to re-render. Optimise only when and where required.</li></ul><p>Even though we’re following the above we decided to have a look at what other options are available to us. Initially two libraries spring to mind: <a href="https://redux.js.org/">Redux</a> and <a href="https://mobx.js.org/">MobX</a>. While I have used Redux on past projects, it is rather verbose with actions, dispatchers and reducers, although it is quite nice to work with. Recently I noticed developers talking about some new state management libraries that have been created. I’m going to take a look at a couple of them here to see what they offer and how they differ from existing approaches.</p><h3>Zustand</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4ej-1rHTfJ5ji7_5XscrWg.jpeg" /><figcaption>A happy bear playing the guitar</figcaption></figure><p><a href="https://github.com/pmndrs/zustand">Zustand</a> is a small and unopinionated library with a simplified take on the <a href="https://facebook.github.io/flux/docs/in-depth-overview">flux architectural pattern</a>. Like <a href="https://redux.js.org/">Redux</a> a store is used to hold state but does not require you to dispatch actions or implement reducers to modify a store’s state, instead hooks are used to read state.</p><p>The main API method is create which is used to create a store and this function receives two arguments: set and get. The function will return a hook to be used within a component.</p><p>The set function is used to set state in the store but it is important to note that this will also <strong>merge in the value you pass to it</strong>. This means you do not need to read the state of the store and merge a new value in manually.</p><p>The get function can be used to read the current state within an action, such as when you want to derive state from the store.</p><p>Here is an example of a booking form containing checkin and checkout dates, and the number of nights derived from those values:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4e1a28c66a765ad31292ca11d3bba09/href">https://medium.com/media/d4e1a28c66a765ad31292ca11d3bba09/href</a></iframe><p>To consume the store within a React component, call the useStore hook. While you can read the entire state of the store, it is best to select the value(s) you need for a component. Otherwise if another value in the store changes, the component will re-render unnecessarily.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f8123bffc5f1c03781f44444fe0e5421/href">https://medium.com/media/f8123bffc5f1c03781f44444fe0e5421/href</a></iframe><p>In the example above two selectors were used to read the check in and check out dates. Zustand though provides a method to select multiple values at once with a shallow compare by using the shallow equality function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf3fb7cc2e6998e6257274cf280230c2/href">https://medium.com/media/cf3fb7cc2e6998e6257274cf280230c2/href</a></iframe><p>Some other nice features of Zustand are the ability to <a href="https://gist.github.com/ihuntington/ec6aa343ea1cd7db3b7a64d2c5c97dcc">add middleware</a> and make use of <a href="https://gist.github.com/ihuntington/ec6aa343ea1cd7db3b7a64d2c5c97dcc">Redux devtools</a>.</p><p>One example of using middleware I particularily like is configuring the set function to act as an <a href="https://immerjs.github.io/immer/">Immer</a> proxy allowing you to mutate deeply nested objects:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e302cb4755754de2a3170f3088f050cc/href">https://medium.com/media/e302cb4755754de2a3170f3088f050cc/href</a></iframe><p>To summarise, Zustand builds on top of great ideas from Redux and simplifies the flux pattern while having a small API and bundle size (1.7kb minified).</p><h3>Atomic state management libraries</h3><p>In 2020 two new libraries emerged; <a href="https://recoiljs.org/">Recoil</a> from Facebook and <a href="https://docs.pmnd.rs/jotai/introduction">Jotai</a> from the same team that made Zustand. Both libraries solve the following problems:</p><ul><li>Performance in large React trees where components in different branches of the tree need to stay in sync.</li><li>When context providers are coupled to individual components. Otherwise if multiple component’s state were in the same provider, whenever the state changes all the components will re-render.</li><li>Providers that need to be dynamically inserted at the root of the tree</li></ul><p>The solution that both libraries implement is to have small, shared units of state called “atoms”. An atom can be subscribed to by components, multiple atoms can be composed together, and atoms can be used to derive data from state.</p><p>It should be said that Recoil was created to solve some specific problems in a large, interactive app at Facebook where there were also requirements for persistence, robustness and some developer-centric functionality such as time-travel debugging.</p><p>I highly recommend watching <a href="https://youtu.be/_ISAA_Jt9kI">Dave McCabe’s introduction to Recoil video</a> that was shown at React Europe. Dave goes through the various problems that Recoil solves with some helpful diagrams and demos. These principles are also applicable to Jotai.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F_ISAA_Jt9kI%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D_ISAA_Jt9kI&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F_ISAA_Jt9kI%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/220b61dbcebf1e04596ad47511c1c7b0/href">https://medium.com/media/220b61dbcebf1e04596ad47511c1c7b0/href</a></iframe><p>There are couple of key differences between the two libraries:</p><ul><li>Recoil requires atoms to have a globally unique string key, whereas Jotai compares objects referentially</li><li>Recoil has support for <a href="https://reactjs.org/docs/concurrent-mode-intro.html">React concurrency mode</a></li><li>Jotai has a smaller and more concise core API</li></ul><p>For an even more in-depth comparison between the two libraries I recommend reading <a href="https://blog.logrocket.com/jotai-vs-recoil-what-are-the-differences/">Jotai vs. Recoil: What are the differences?</a> by Yaroslav Lapin.</p><p>Here I’m going to have a look at Jotai more in-depth because it has a smaller API and I’m following on from <a href="https://kentcdodds.com/blog/application-state-management-with-react#what-about-performance">reading recommended advice</a> by <a href="https://kentcdodds.com/">Kent C Dodds</a> in his article <a href="https://kentcdodds.com/blog/application-state-management-with-react">Application State Management with React</a>.</p><h4>Jotai</h4><p>The core functions are atom and useAtom hook (which is similar to React.useState) and Provider. When creating an atom you can pass it an initial value or you can create a derived atom. There are three types of derived atom:</p><ul><li><strong>read only:</strong> pass a read function as the first argument and this will have access to a get function.</li><li><strong>read and write:</strong> pass a read function as the first argument and a write function as the second. The write function will have access to a get, set and update methods.</li><li><strong>write only:</strong> pass null as the first argument and a write function as the second.</li></ul><p>With that, here is an example of the booking form using a derived read atom to get the number of nights based on checkin and checkout:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d658ac65d45aaec9f59f212e188b939d/href">https://medium.com/media/d658ac65d45aaec9f59f212e188b939d/href</a></iframe><p>We can then consume the atoms within a React component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c98c53e7b5090a606499ab90f6eeb58/href">https://medium.com/media/2c98c53e7b5090a606499ab90f6eeb58/href</a></iframe><p>The provider can be passed a set of initialValues and ascope property to scope atoms, this is useful if creating a component library for instance.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2398f47562509f795118cc364889d788/href">https://medium.com/media/2398f47562509f795118cc364889d788/href</a></iframe><p>It is worth noting that read atoms can be asynchronous, however, when it comes to server-side rendering the atom will need to <a href="https://docs.pmnd.rs/jotai/guides/nextjs#you-can-t-return-promises-in-server-side-rendering">return either pre-fetched data or an initial value</a>.</p><p>Jotai also comes with a set of <a href="https://docs.pmnd.rs/jotai/api/utils">utility functions</a> and <a href="https://docs.pmnd.rs/jotai/api/devtools">developer tools</a> which mirror some of Recoil’s own functionality. Jotai also has a set of integrations with other libraries that include Immer and <a href="https://docs.pmnd.rs/jotai/integrations/optics">Optics</a>.</p><p>As an alternative to React Context and useState, Jotai provides a number of features in a small package.</p><h3>Our next steps</h3><p>Earlier this year we decided to move our component library to use CSS-in-JS. <a href="https://ruijdacd.medium.com/">Rui Duarte</a> has written an <a href="https://medium.com/plumguide/migrating-to-css-in-js-part-1-e93f60b57eba">article explaining the process</a> and the reasons why. One of the reasons was to improve performance but at the same time it gave us an opportunity to improve how state is managed within some components.</p><p>As an example we have refactored a slider into smaller components along with introducing it’s own provider. This enables use to have more <a href="https://kentcdodds.com/blog/compound-components-with-react-hooks">declarative compound components</a> and to create multiple variations of the slider too.</p><p>While we’re continuing to improve how we manage state on existing projects with React Context, we have some ambitious and state heavy projects coming along soon and we’re excited to put some new approaches to the test.</p><h3>Final thoughts</h3><p>Before reaching for a library though there are a couple of ways to make sure your app is performant:</p><ul><li>Keep state local until it needs to be shared with a common ancestor</li><li>Separate state into multiple logical providers</li><li>Keep providers close to where they need to be used</li></ul><p>Hopefully I have given you a flavour of a couple of libraries that interested me when researching into React state management. I’m looking forward to using them in the future and exploring their capabilities further on personal or work projects.</p><p>If you’re using one of the libraries mentioned and have some advice, or I’ve missed something, please share.</p><p>If you’re like us and love to share your work with your peers, and interested in challenging problems and scalability, <a href="https://boards.greenhouse.io/plumguide"><strong>we are hiring!</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5fc46a247e65" width="1" height="1" alt=""><hr><p><a href="https://medium.com/plumguide/a-look-into-react-state-management-in-2021-5fc46a247e65">A look into React state management in 2021</a> was originally published in <a href="https://medium.com/plumguide">Plum Guide</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>