Syntax Video
React vs Vue - Sharing State and Complex State Updates
- 0:00 Intro
- 1:20 Brought to you by Sentry
- 1:51 Lifting State Up
- 2:20 Prop Drilling
- 3:08 React Context API
- 4:00 Vue shared module
- 4:40 Vue provide / inject
- 5:18 React Context API Example
- 8:49 Vue provide / inject example
- 11:54 React Rendering Considerations
- 13:14 React use-context-selector
- 14:54 Vue Rendering Considerations
- 16:06 React - Persisting State Across Pages
- 17:01 Vue - Persisting State Across Pages
- 18:34 React State Management Libraries
- 19:08 React zustand Example
- 20:50 Vue pinia Example
- 21:53 destructuring pinia stores
- 22:43 Deeply Nested State Updates
- 25:51 React - Mutable State Updates
- 26:33 structuredClone in JS
- 27:06 State Updates in zustand
- 27:26 More Examples
- 27:46 Next Time
- 28:09 Thanks!
Intro
over my many years of writing software I've built a lot of things with View and a lot of things with react and one of the most common things you want to do in a front-end application is share data and state between pages and also between components and in this video we're going to take a look at how that is done in both View and react now this is the second video in a multi-part series where we're taking a look at the same app that has been built with both View and react in the last video we took a look at this form validation example and we mainly highlighted how state is managed within components we also took a look at template syntax and in this video we're going to talk about sharing data between pages and components with this cart example so for instance you can add things to the cart the status is displayed there we also have a cart page you can change the quantity or remove it from the cart there but how is all of this working how are we sharing that data and if we take a look at the component hierarchy there's a lot of different components that need access to this data and need to be able to modify this data right we have the cart status we have the products page which has a
nested product compon component and then it has a button that needs to add to the cart we have the cart page with the product and cart component it has a remove from cart button but all of these things need access to the same data and they need access to the same actions that modify that data how is it done let's dive in my name is CJ welcome to [Music] syntax now this video has been brought to you by centry centry is an error monitoring platform essentially it allows you to keep track of all the errors that are happening in production it categorizes them it can alert you when they happen it's really great you should definitely be using centry if you're running code in production and centry has sdks for many things including react and view so if you want to add it to your react app they have an SDK for that if you want to add it to your view app they have an SDK for that if you have any other type of app they also have an SDK for that where you can add Sentry and start tracking errors in production now when you're trying to solve this problem of sharing State between pages and components one of the first bits of advice you'll get is to
Brought to you by Sentry
Lifting State Up
lift the state up so ENT Al if all of the state and methods are defined at the top level then all of that data and state can somehow be passed down or accessed from these nested components right so let's say we have some shared state which includes like items in the cart and then also actions you can perform on the cart we can Define that at the top level and then somehow get access to it in all of our nested components now one of the ways you can solve this is with props so you could potentially Define all of that state and data at the top level here and then pass it down as a prop to all the components that need it the issue is if any nested component also needs that data it also has to be passed there right so even in the simplest case of this cart status component the app has to pass that data down to the navbar and then the navbar needs to pass that data down to cart status it gets even worse when you have more levels of components because the app would need to pass it down to the page the page passes it down to the product component which then can access it in the add to cart button this is
Prop Drilling
known as prop drilling I've worked in COD bases that have a lot of this and it can get cumbersome very quickly um so this is one solution but there are other ways of doing it that are built into to both View and react so if you take a look at react they have the context API and the way that that works is you can define a context that has some of this shared State and methods and then you pass it into the provider and the provider is a top level component that must wrap all of the children that want to get access to that data and methods so context provider is at the top here and then every sub component is going to be able to get access to it but without having to pass props because in any given component you can use the use context hook which is built into react specify which context you want access to and you can get access to that data and so this is nice because you can do it at any level of your components so in these deeply nested components I don't have to pass the props all the way down I can just say use context right there wherever I need it and so this is called
React Context API
the context API it's built into to react and I'm going to show you an example with that in view there are a couple ways to do it now in view your reactive variables actually don't have the same rules as like the used State hook does inside of react because technically you could Define all of your methods and reactive variables in a module and then just import it directly into any component that wants to get access to that data now I wouldn't recommend this for large applications but technically this is one way to do it now uh you don't have to pass the props literally Define it in one spot and then import those variables wherever you need them but view is smart enough to see those changes regardless of of where they're changed or where they're accessed but again in larger code bases this could get a little bit messy so Vue actually does provide an API called provide and inject and it works very similar to the context API where essentially at your top level you say provide you give it a name and pass in the initial State and methods and then anywhere else in your component
Vue shared module
Vue provide / inject
tree you want to get access to it you say inject and you pass in the name of the thing that you would like to get access to and this can be done at any level of the component so very similar to the context API uh but you don't have to wrap your component Tree in that provider component you can just call Provide and then inject in any of the components so this is how it all works let's actually take a look at the code we'll first dive into react and see how this is implemented with the context API so first I've defined a type that describes all of the data and methods that I want to share in my app and we have items which is the list of items in the cart we also have total items which is total number of items take Tak into account the quantity of each item in the cart we also have total which is the total cost of the cart and then three methods to operate on the cart we have add to cart update item and cart and remove item from cart so now with this type I have defined a context so in react we have this method called create context I've told it that it should be of this type and here I'm providing an initial value now technically you can pass an initial value like null but then
React Context API Example
everywhere in your code base where you try to use this context you first have to check if it's null I don't like doing that so I kind of just have this empty value passed in here then in our top level component we need to actually use this context so here in my shop application I have a folder called context and I've to find this context inside of here and if we take a look at the shop component you can see that I'm importing that defined context there and then right here at the top of my shop component I have card context. provider so essentially everything that's a child of this component is going to get access to the card context value that I pass in here so I have a used State here that defines that of items in a method to update them and then cart context has all of the other things that we need for this context so we're passing in the items we have total items in total which are calculated based on the list of items and then we have those three methods for operating on that list now you can see here I'm using use memo and that's because I don't want this provider to render unless the items have actually changed so essentially we have
all the things that we need we've bottled that up into a use memo and this will only get recreated if the items array has changed now from here in any nested component I can use the Ed context hook so you can see that I actually have some routes set up I have the products page and the cart page but you'll notice I'm not passing any props here I've just rendered out those components if we take a look inside of the cart page we can actually see where we're using this context so if I go in here to pages and then cart we can see up at the top I have use context so use context comes from react and then I pass in that context there that I created in the context folder so essentially what will happen is because this cart component is a child of the cart context provider this hook right here is going to get access to the data that was defined and passed into the provider here so this one called use contacts actually gives me access to those things and here on the cart page I can iterate over the items in the cart and list them out I can also show like the status of the cart as well now another spot where we're using the context is inside the product component
itself if you look at the products page the products page is just a list of product right it doesn't actually need access to the cart but each individual product needs to be able to add itself to the cart so if we look at the individual product component we can then see that it actually uses the context as well and all it's pulling from the context is that add to cart method so in here we have a little button and when it gets clicked it is able to actually add itself to the cart by calling that method now on the cart page we are listing out each carded product but a carted product needs to be able to change its quantity in the cart and also remove itself from the cart so we're using the context in there as well so if we take a look at components and then C Ed product we can see that we're using that context but then we're bringing in those two methods that an item in the cart needs to be able to call and then lastly we have that cart status button which shows us how many things are in the cart and the total price right now and that's just bringing in total and total items and then reading them out there in the status bar so that was the context API inside of react now let's take a look at the provide and inject
Vue provide / inject example
API inside of view now here I have a type that describes my provider very similar to the type that we described in react but I'm using reacted and computed refs so these come from View and this is how we can Define variables that are reactive inside of our view and also variables that automatically get computed or recalculated when their dependencies change now to Define my provider I have a folder here called providers and I Define the cart provider inside of it now here I've exported a function called provide cart and this is what I'll actually call it the top level component now technically I could write this code in the top level component but I like to give it a nice name and then also include the type here so don't have to do that wherever I uh provide this cart you can see that I give it a name and essentially anywhere that calls inject whenever it references that same name it's going to get that value and then I have a function here that creates the cart and this is where I've defined all of my variables and methods so we have items which is a reactive array we have total items and total which are
computed so these automatically recalculate if their dependencies change and then we have our three methods for operating on that items list now this method create cart just returns an object that has all of those values on it and that's what we're passing in here now any component I want to use this in I can bring in this inject cart method now technically you could write this code in any component where you want to inject this provider but I want to put it in a nice named function here so I don't have to remember the string name of the cart or anything like that so any component that needs this data can just import inject cart and call it now you can see I'm also passing in create cart here this just defines the value if for whatever reason there's a component that called inject cart but isn't a child of a component that that provided the cart this makes it so that we don't have to check if it's undefined it's going to have an initial value there but at the top level I do want to provide the cart data so here in my shop view I have imported provide cart and then invoked it and so now shop view is at the top level every child component is going to get access to the data that was defined
here with provide cart now here I have this router view this is where both the products page and the cart page are going to get rendered out so let's take a look at those first if we look at the cart page we can see here that I am importing that inject cart function I'm calling it and then I get access to the items that I need so I'm able to iterate over the items here and then also render out an empty message if there are none and then also display the status of the cart now if you look on the products page it doesn't need access to that provider because it's just listing out the products themselves but inside the product component we need to be able to add this item to the card so if we take a look at components and then product we can see that we import inject cart and in this case we're just getting access to that add to cart method which we can call whenever that add to cart button is pressed now similarly on the cart page we have that carted product it needs to be able to update the quantity in the cart and also remove itself from the cart so we invoke inject cart get access to those two methods and then we can call them whenever those respective buttons are pressed lastly if we look at
the cart status very similar we're importing inject cart getting access to those two things that we need and then showing the status there now on the surface both of these implementations are very similar right to find your stuff at the top any component that needs it can just call a method to get access to it but there are considerations to be made when we are actually rendering out the app so here inside of react I have the react Dev tools installed and then on the profiler tab I have highlight updates when components render checked and so this is nice for debugging components you can actually see when they render but watch what happens when I add this product to the cart this entire products page rerenders um and that's actually a limitation of the context API but if you think about it the products page only needs the add to cart method right it doesn't actually need any data from the cart it just needs that method but still because we're using the context API the entire subtree is rendering whenever that context data changes now this is a limitation of the context API even
React Rendering Considerations
though I'm using use memo here still the entire sub tree needs to rerender when that value changes now there is an RFC that has been opened since 2019 called context selectors and essentially this would introduce a way to get access to specific items in the context without needing to get access to the whole thing which causes a rerender for any component that calls used context uh but yeah this was created in 2019 and it still has not been added to react yet but there is a library in userland it is called use context selector and essentially what you do is if you bring this library in you can use it to create your context and use your context but then for anywhere that you use a context you can pass in a selector function and the selector essentially just grabs the specific things that are needed in that component and then that component should only render if the things that it's selecting have changed now I went ahead and tried this out so in the repo you can see there's another folder here called shop context selector and
React use-context-selector
basically all I've done is I've replaced the call to create context with the one provided by used context selector and then anywhere where I need the context I'm using the use context provided by the use context selector so let's take for example the speciic specific product component right so if I look in components and then product it needs access to add to cart that's the only thing that this component needs access to so ideally it should never render unless the add to cart method has changed and so here I'm calling use Contex selector passing in my context and then my selector is just grabbing the add toart method now unfortunately I couldn't get this working so so in the react app I've swapped it out so it's actually using the context selector shop now but we're still getting renders and uh I couldn't figure it out so maybe I'm doing something wrong we can see here now it's using context selector but still this is rendering even though this component is only getting access to the add to cart method now I have a feeling it could be how I'm actually setting up
the state here with use memo if you know a way of fixing this please let me know in the comments but I couldn't get it working even with trying to use the use contact selector library now in view we actually don't have this problem the reactivity system in view has what's known as fine grained updates so regardless of where you define state the only places that are going to render are the places that actually access it now uh I do have the Vue Dev tools installed here but I don't know of a way to do the same rendering flash like you see inside of the react Dev tools but it's actually pretty easy to implement so here inside my view app I'm adding a mix in and basically this adds this updated method to every single comp component in my application and I can get access to the underlying element and I'm just adding some CSS here so when that component is updated it's going to flash and outline and so I can do that with this little plug in here honestly this should just be added to the The View Dev tools but now with that enabled you'll see that
Vue Rendering Considerations
when I add to cart the only thing that updates is this cart status up here right and that makes sense right because that's literally the only thing that's changing on the page right now um nothing about the product component has changed so the only thing that needs to render is the area that's actually accessing that cart status and you get this for free in view you don't have to do anything special because that's just how the reactivity system works now another consideration here is where you actually Define your provided data so in the react example we Define that card context provider at the top of the shop component right so let's say I add a few things to the cart if I navigate away from this shop component that component completely unmounts which means it removes that provider so when I go back to the shop page the data is no longer there now the only way to fix this and make it so that the data persists regardless of which page I go to is to take that c context provider and move it up in the tree right so right now it's defined here in the shop component but if I want this data to stick around even
React - Persisting State Across Pages
when I'm not on the shop page I'm going to need to take this context I've defined and the provider and move it up and in this case I would probably move it to the app so I would have to Define it here and you see this in a lot of react apps essentially you have a bunch of providers all wrapping the app to make sure that that data is accessible anywhere in the application now over in the view example I actually implemented it so that it would behave the same way right so if I add some things to the cart and then navigate away all of that data disappears but to make the data actually persist is actually fairly simple so you can take a look here in view where we defin this provider and you can see that when I Define it I'm invoking create cart here but if I want this data to persist all I have to do is move this into a variable right all I have to do is say cart equals that I can pass it in here and then I can pass it in here as well and now because this method only gets called once when the application is created now this data persists throughout my application so now I can just add things to the cart but if I
Vue - Persisting State Across Pages
navigate away when I come back to that component the data has persisted because this cart was only created once when the application started now the reason this works is because these reactive values that we Define inside of VI aren't limited to being defined inside of component components like they are inside of react with like the US state hook these can actually be defined anywhere and then they will persist and your views will still continue to update and so this is similar to the diagram that I showed earlier where you can actually Define these things at the top level and then bring them in anywhere but this is a nicer way of doing that because it's a bit more encapsulated right instead of just importing this variable directly you actually have to call inject cart so it keeps things a little bit more manageable but still the the way of sharing data here is just a lot nicer because I don't have to worry about like where that data is defined in the component tree I can literally just Define it inside of the module here now in the world of react typically teams reach for other libraries uh because of that issue that I showed with the
React State Management Libraries
context API where any component in that subtree will be rendered if the context value changes and uh there are a lot of different State Management libraries in the ecosystem that people might choose from so there's zand there's joai there's also recoil and then also Redux which is a bit more involved but all of these actually provide a solution for sharing State throughout your application and typically does not have that issue of rendering the entire subtree of the context and so for my shop example here I actually brought in zand and we can see how that was implemented so here I've defined a store we have that exact same type as we saw for the context earlier and then I have a few methods for calculating total items and total and then a little helper function here that takes in a new list of items and then recalculates the total items in total there but then all of these methods are used inside of this store so with zon you can say create and then specify all of your initial State and then you can provide methods that actually can operate on that state and
React zustand Example
so here we have the set method and essentially we get access to the state and then we can update the state accordingly um so zand is pretty nice um I will say that I don't like that I had to Define these methods here um essentially these are computed values right they're dependent on the items array I saw there are a couple of plug for Zan for adding computed I didn't exactly like their API um and it would be another library that I had to bring in so ultimately reading around people were saying yeah instead of computed State really you should just recalculate things yourself whenever other things change so that's kind of how I implemented it here but uh the API is pretty nice right I can Define this store here this gives me this hook called use cart store and then in a component that actually needs it so let's look at that product component again we can call the hook and then pass it a selector of the thing that we want so in this case I'm asking just for the add to cart method on that product component and so now if we actually watch the reenders here only this area
of my app is re-rendering because usand actually allows us to only pull in the things we need and then the components only rerender when those things have changed and in this case the add to cart method isn't changing only the status of the cart is changing now in the world of view we typically reach for this Library called Pia instead of using the provide and inject API directly honestly I I didn't even know that API existed before I made this video because every app you come across is pretty much using Pia there there aren't really any other choices here which is really nice and especially because Pia is maintained by the core team so if you need this kind of solution you just bring in the Pia library now I implemented our same shop example here with P you can see I have a stores directory and then our cart. TS and with Pia we use this Define store method pass in the name of the store and this gives us a nice reusable hook that we can use anywhere in our app so I Define this once here any component that needs access to this we'll just call use cart store and the way we Define all the data and the methods is exactly the same as when I was showing with provide and
Vue pinia Example
inject right I have all of my computed values my data here and then I have the methods that can operate on it and this just returns an object and so if we take a look at our product component you can see that it can call use cart store and then it gets access to that cart itself now the one caveat when working with Pia is if you are destructuring some of those data properties from your store you do have to use one of their helper methods so let's take for example the cart status component this component uses total and total items from the store but I cannot destructure those directly from the store itself right if I try to do that you'll notice here that these are just the values themselves they're not the actual reactive values so if you want to destructure you do have to use their helper method called store to refs which basically takes those properties off of the store and then wraps them in uh either computed or reactive or whatever they're actually defined as inside of the store so that way when you're using these values down here they are reactive so that is one
destructuring pinia stores
caveat it's it's not amazing um but that is one thing you have to take into account when you're basically destructuring these reactive values from a store so that's it for sharing State between pages and components but the last thing I want to take a look at is how our state is actually updated in both View and react now we took a look at this in the last video but as your data gets more complex your State updates get more complex and so let's take a look so here inside of react I have this remove item from cart method right and we defined our items using use State and I want to be able to remove an item from a cart based on its ID and size properties and so the method for this is fairly simple we can just use filter right so we have to call set items with a copy of the state and then remove that item that we're trying to remove and so in this case we just use array filter to pull that item out that we don't want in the cart anymore fairly simple inside of view we can modify that items array directly so first we find
Deeply Nested State Updates
the index of that item and then if it exists we just remove it from the items array and so I defined items as reactive here we can just modify it directly and then the view will update accordingly but now let's take a look at update item in cart and so this method is used over here on the cart page if I want to change the quantity of an item and so in order to do this we need to create a copy of the items array so I'm using a map and then for the specific item that I'm trying to update if I find it whenever I'm mapping I need to copy that item and then update the quantity accordingly and for every other item in the list I don't need to copy it it can stay exactly as it is because its quantity hasn't changed if we take a look at how this is done in view first we find that element using find index and then if I found it I can just change the quantity directly I don't have to copy it or the array or anything like that and then lastly if we take a look at add to cart this one is the most complex because let's say I'm on the
products page and I want to add something to the cart that is already in the cart if that's the case then I need to adjust the quantity of the existing item in the cart right I don't want to add a new item so if I add another small one I don't want to see two smalls on this page I want the existing one to increase its quantity uh but if I add large it should be a separate item in the cart so we have to take into account all of that logic in our add to cart method and so here in react first we search for that item in the cart if we didn't find it then that means this is a new item it's not already in the cart we just need to put it on to the end of the array so I'm creating a new array spreading the existing items that are in the cart and then creating a new product in cart object here that has all of those properties now if this item did already exist in the cart we actually want to increase the quantity so we do a similar update as to what we did for update item in cart but instead of just setting the quantity directly we increase the existing items quantity by that specific quantity and you see here again I need to copy the existing object and then update that property but for all the other items I don't need to copy
them they can stay exactly the same if we take a look at how this is done in view first we check to see is the item in the cart if it is we just increase the quantity if it's not we push in a new item into that array and so for me this is one of the highlights of view is being able to mutate State you just have to jump through a whole lot less Hoops now uh there are solutions for this in the world of react so there is this Library called emmer and it allow you to write code that looks like you're modifying the state but under the hood it actually is creating copies for you and for example it provides this method called produce you pass in the thing that you want to modify you write your code that just modifies it but it's actually creating a copy and then under the hood updating that copy so in react codebases that use this Library the State updates are a lot nicer but I've worked in a lot of react codebases where nobody knew about libraries like that and so you had all of this like spreading code and mapping code all over the place and this only gets worse when you have deeper nested arrays deeper nested objects the spreading can
React - Mutable State Updates
definitely get out of hand now built into JavaScript there is this method called structured clone which allows you to create deep copies of objects um so you could use this but in my specific example here I actually don't want to deep copy right because all of the items that haven't changed I don't need to copy those can stay exactly the same the only ones that I actually want to copy are the ones that have changed and so a structured clone technically you could use that but you're going to be doing more work because you're copying more than you need to and even if you use structured cloning in this example you would still need to go find that item and then update it afterwards so it's not a bulletproof solution now even in the example where I use zand we still have to do immutable updates right so our our code here to do the updates is very similar however zon does have an immer plugins and so that way you would be able to do mutable updates inside of zon and that would definitely be my preferred way of of working with shared state in react you'd have to pull in a couple more more libraries to get everything working so that's it for these examples now I wrote a lot of examples including ones that I didn't
structuredClone in JS
State Updates in zustand
More Examples
even have time to show like this this reducer one but if you want to look at those take a look at the link in the description all the code is there for you to look at also like I mentioned earlier if you saw anything that I've done wrong or maybe you think can be done better feel free to comment down below as well now in the next video we're going to be diving into this image search example which allows you to search for an image it hits an API gets back the response and then we also have some pagination here so we're really going to be taking a look at like async State loading State and then also how I implemented page ination so if you're interested in that definitely subscribe to the channel turn on notifications so you can be alerted when this video comes out thank you so much for watching if you're interested in where you might be able to find this really cool shirt that I am wearing you should subscribe to our newsletter go to syntax. fm/ snackpack subscribe you'll get 15% off swag in the swag store and sometime this week this shirt is going to drop so if you want to be alerted make sure you're on that
Next Time
Thanks!
Quote it with credit and a link. Quoting Syntax