<?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 Nathan Queija on Medium]]></title>
        <description><![CDATA[Stories by Nathan Queija on Medium]]></description>
        <link>https://medium.com/@nathanqueija?source=rss-14747c6db2c8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*BNpw7w18wfIq404Ekdef6A.jpeg</url>
            <title>Stories by Nathan Queija on Medium</title>
            <link>https://medium.com/@nathanqueija?source=rss-14747c6db2c8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 01:53:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nathanqueija/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[How to share state between different packages using React context API]]></title>
            <link>https://medium.com/@nathanqueija/how-to-share-state-between-different-packages-using-react-context-api-40cc0ceda50d?source=rss-14747c6db2c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/40cc0ceda50d</guid>
            <category><![CDATA[react-context-api]]></category>
            <category><![CDATA[npm-package]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[feature-focused-teams]]></category>
            <dc:creator><![CDATA[Nathan Queija]]></dc:creator>
            <pubDate>Sun, 16 Jun 2019 18:24:50 GMT</pubDate>
            <atom:updated>2019-06-16T19:43:02.490Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to expose and share self-contained state between different packages using React context API</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*etmNMUeXlTxDoP-E" /><figcaption>Photo by <a href="https://unsplash.com/@othentikisra?utm_source=medium&amp;utm_medium=referral">israel palacio</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I’m assuming that if you’re here you’ve suffered enough when your React application (and your team) started to grow and it was very difficult to control the state of your application that probably (if you use Redux) followed the same pattern of having only one store as the single source of truth with many awesome components connected to it.<br>That being said, I assume you already have some knowledge about:<br>1. Redux (I’m not going to use redux in this application as the title says and neither is my intention here to say that you should not use Redux anymore. I&#39;m trying to show an alternative for a particular use case, but it’s interesting to know a little about Redux in order to understand the difference of what I’m going to propose in this article).<br>2. <a href="https://reactjs.org/docs/hooks-intro.html">React Hooks</a><br>3. Specially <a href="https://reactjs.org/docs/hooks-reference.html#usecontext">useContext</a> and <a href="https://reactjs.org/docs/hooks-reference.html#usereducer">useReducer</a> hooks</p><p>Ready? Let’s go!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*ONBTaxzVm8YhC8rs6XVjRw.png" /></figure><p>The most basic example of a React application using Flux pattern to manage state.</p><p>Take a look at the example image above. Surely you’ve worked on some project with a structure similar to that.<br>In short, you have a store as the only source of truth in your application. To consume the global state of the application you wrap your application with a Provider that allows any component down the tree to be able to connect to the store and trigger actions that will be managed by the reducers of your application that will consequently return a new state of the application. With this status update all the components connected to the store that are interested in that particular piece of the state that has changed will be notified and rendered again. Isn’t it beautiful? I think so.</p><h3>Understanding the problem #1: the need for a composite application built with shared features</h3><p>Now imagine the following scenario: you and your team are not just building one application, but the business has grown and you are now developing two, three or more applications and you start to realize that there are features that are used in more than one application. Repeating the same code from the same feature in two different repositories is out of the question. Imagine just having to keep changing the same thing in two or more different places when this shared feature needs to be changed.<br>Now you not only have several complex features that need to be shared, but your team has grown a lot and you can not have just one team that takes care of the entire application, you want to have feature focused teams.<br>What to do then? 🤔🤔🤯<br>Your team decide to separate each feature in its own repository and publish them as isolated packages in NPM so any of your applications that want to use the features can install them separately so you can have small and fast feature focused teams that develop the feature UI and state isolated from the rest of the application. Easier to maintain. Easier to test. 🚀🚀🚀</p><p>For the sake of simplicity let’s imagine that we will have two super complex features: <strong>Todo list</strong> and <strong>Counter</strong>.</p><p>Let&#39;s try to visualize the new structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ucygVZ5k_ckDCRUzGAUFxw.png" /></figure><p>You’re happy with the result so far. Teams are agile and focused on their features. Everything is isolated and you are no longer having big problems with a store that knows too much. Your application is using shared resources which in turn are divided into smaller features that compose your application. Software development is largely about software composition. Smaller parts that together form something bigger.</p><h3>Understanding the problem #2: the need for a shared state between features</h3><p>Now imagine that one day your Product Manager says that your <strong>Counter</strong> feature will now depend on your <strong>Todo</strong> list feature. You now need to initialise your <strong>Counter</strong> with the amount of <strong>todos</strong> you have on your list and in one page you need to display just the counter, no need to have buttons to update it and if you update the counter in its original page this counter that is display-only in the new page needs to be updated to.</p><p>But, wait… If both features have their own state isolated how do I know from the Counter feature how many todos I have remaining? Will I need to have my global store back and have UI only isolated features? 😭 Will I need to mix state from one feature into another? What about my beautiful piece of art, I mean, software composition that I just created?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SytoBax6L4HtdCrlMfoAGA.png" /></figure><h3>React Context API to the rescue!</h3><p>Ladies and Gentlemen, right from the <a href="https://reactjs.org/docs/context.html">docs</a>, I introduce you, React Context:</p><blockquote>Context provides a way to pass data through the component tree without having to pass props down manually at every level.</blockquote><blockquote>In a typical React application, data is passed top-down (parent to child) via props, but this can be cumbersome for certain types of props (e.g. locale preference, UI theme) that are required by many components within an application. Context provides a way to share values like these between components without having to explicitly pass a prop through every level of the tree.</blockquote><p>In short, with the context API you have two players: the <strong>Provider</strong> and the <strong>Consumer</strong>.<br>Think of the Provider as the classic Provider component of <a href="https://github.com/reduxjs/react-redux">react-redux</a>. You wrap your entire application with this Provider and this way you do not need to pass props down the tree. When you have the need to have access to the state of your application you connect your component to the store.<br>Think of Consumer as a component connected to your Provider. Similar to the process that is done with the connect method of react-redux.</p><p>The difference is that with React Context API you don&#39;t need to have just one Provider and one context, you can have how many contexts you need, even separated by domain, for example, a Todo context and another Counter context that has state only related to their own domains.</p><p>You may ask yourself that you can reach the same result with different reducers using combineReducers, but in the end of the day you will still have one store, now it&#39;s my turn: how do I split this store into separated packages? Maybe it is possible, but I don&#39;t know if you can reach that easily.</p><p>My proposal in this article is to ship these self-contained features as modules to NPM and within the package export the whole feature connected to its isolated state in case you need to use the whole feature and export the feature state as well in case you need to use only the state in other pages of your application. Let&#39;s see how that works?</p><p><strong>Feature structure</strong></p><p>I&#39;m going to propose the following basic file structure for these self-contained features:</p><ol><li>[feature].js contains the logic for the feature connected to its context</li><li>context.js exports the context Provider for that feature and a custom hook to act as an isolated Consumer.</li><li>reducer.js is the reducer that handles the state changes</li><li>actions.js as the name says are functions that dispatch actions</li><li>index.js exports the Provider and the custom hook from context.js file</li></ol><p>And of course that this feature can have its own internal components. I&#39;m not saying that you should keep all your feature logic in one file. This is a basic structure just for the sake of simplicity.</p><p>Let&#39;s go through the code for the <strong>Counter </strong>feature as it is simpler to understand. You can find the repository that I created at the end of this page. I am not going to go through the <strong>Todo </strong>feature code because it follows exactly the same pattern.</p><p><strong>Counter.js</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P1oT-Y787EJL2Z2VYf07Ug.png" /></figure><p>A simple presentational component. Do you see the useCounter hook being called? This is how we consume the state for this feature.</p><p><strong>context.js</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l6Mg1kYQkfTmhyGeXz_LFg.png" /></figure><p>Here I am exporting the Provider for this feature with its initial value. The value for this Provider will have the state as the functions to mutate the state. I am calling createActions function with the current state and the dispatch function given by useReducer hook. The createActions function will return an object with functions that will dispatch actions. Let&#39;s see how that works.</p><p><strong>actions.js</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FdcZQDo1E9VFnLAFa9XAtw.png" /></figure><p>Simple, right? If you used Redux before this looks similar to you. This structure reminds me of action creators. The difference is that instead of returning actions from these functions I am directly dispatching them.</p><p><strong>reducer.js</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HROfkDsMAqO9hzdiP8MyLg.png" /></figure><p>Now it&#39;s time to see how to use this, right? Let&#39;s do it!</p><p>Imagine that both features were published to NPM and we&#39;ve added them to our package.json file. I&#39;ll assume that @ madebyme is our organization account.</p><p>This will be the basic structure for our main Application:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TRJunQ2hNDY3S_OV9IAPaA.png" /></figure><p>Here I am importing both Providers. We need to wrap our application with the respective Providers, otherwise we won&#39;t be able to use our custom hooks consumers. I am wondering if I would be able to create a combineProviders function so we don&#39;t need to wrap our application with a lot of Providers, you can imagine as our application grows how many Providers we are going to have in this tree, but let&#39;s wait for the next chapters.</p><p>It is worth to mention that with React Context API you don&#39;t need to have the Provider at the top level of your application as we are used to do with react-redux. You can use the Provider in any level of your application, just make sure the Provider is at least one level above your consumers.</p><p>The idea is that our Application will have 3 pages.</p><ol><li><strong>Todo PAGE: </strong>Using the self contained <strong>Todo </strong>list feature.</li><li><strong>Counter PAGE: </strong>Using the self contained <strong>Counter </strong>feature.</li><li><strong>Mixed PAGE: </strong>Using only the state from <strong>Todo </strong>and <strong>Counter </strong>features so if you change the state for this feature every single place in your application that is connected to the context that has changed will be updated.</li></ol><p>Let&#39;s go through the pages now.</p><p><strong>Todos PAGE</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nduk1s3F0zLwxorOxBRlHQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l2SOdFC8IFYdNnZynEAeIA.png" /></figure><p><strong>Counter PAGE</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o3XCpLJAExl-SxSgYh3E9g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YzBKBNv7E54kPhQHE2_a2A.png" /></figure><p><strong>And finally the mixed PAGE that uses only the state from the features:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r389g_oAfDNFa8-3pGrnmg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rlZGffagxrjZ-naqO4Cueg.png" /></figure><p>So now that we have all pages setup, if you add a todo from <strong>Todos </strong>page the state shape being shown int the mixed page will be updated and vice-versa. The same applied for the Counter page.</p><p>To finish, with this approach your features are packaged with UI and state isolated from the rest of your application and exports the entire feature if you want to use it without worrying about its state as it also exports the state of the feature in case you need to compose a page with combined state from multiple features. Building blocks that are used together :)</p><p>I created a repository with the code for this example. You can find it here:</p><p><a href="https://github.com/nathanqueija/multiple-providers">nathanqueija/multiple-providers</a></p><p>I am still researching and playing with this proposal, especially testing the performance and the re-render cycle when a context is updated. I&#39;d like to understand better how this is propagated to components that are not consuming the context that was updated. I am following this <a href="https://github.com/facebook/react/issues/15156#issuecomment-474590693">thread</a> to understand better how it works so expect the repository to be updated soon.</p><p>I would love to know your opinion and if you have alternatives for the problem that I raised in this article feel free to contact me. You can find my e-mail in my Github profile and though I&#39;m not a heavy twitter user you can find me here too: <a href="https://twitter.com/nathanqueija">https://twitter.com/nathanqueija</a>.</p><p>That&#39;s all folks! Thanks for your patience reading this book.</p><p>Let&#39;s keep learning from each other, sharing what we know to help the community to grow and build a better world together.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40cc0ceda50d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>