How to useContext with useReducer

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello everybody and welcome back to my channel it's always great to see your face again I hope it's good to see my face again because I am back this week with another exciting riveting entertaining episode of information education and react it's gonna be another episode about react I promise not all these episodes will be about react although you might enjoy most of the reactor photos but that's fine I like to try different things so that will come in some future episodes this week I think I'm going to be concluding my series of videos where I have on this log in form demos that I've been using it has been such a wonderful base example that I can kind of build other tutorials on top of and I just wanted to milk it dry one last time with this video today I'm going to be showing you how to use the new context feature of react in the context of use reducer that pun was not intended unfortunately those words overlap that way I have had another video I think in the past when I covered all of react sixteens new features where I talked just about how context was made no longer this dark dirty secret of react but now a nice officially supported wonderful way of sharing data in your react tree you want to see that video click back the link will be in the description below but today I'm gonna show you why taking a use reducer with immer and adding some context makes for three technologies that will have your application very easily supporting flexible data as a changes in your application be able to have use reducer to emerge to easily update the data and then using contacts usually easily pass that information down to any child descendants node and also letting those childhood Senate nodes also easily obtain that data all the way up in those parent nodes if you are curious about how this is going to look like then you are in luck because let's start showing the code okay so let me give you a tour of where the code is right now if you've been following along in this series awesome thank you if you haven't I do recommend you check out my previous videos talk that trying to give you the basis for where the code is right now so that when I scroll down in this code and you see this using a reducer you ain't confused just click back maybe to before you'll be filled in and be in the know the designated Nizhny know that no wasn't busy you know you have to see me talk some more so you'll get to know what I'm talking about so what I've done in this demo is I've kind of built it out so you've seen the login form before for my previous demos where you put in username password you got a log it add log in that's fine but I've added for demo purposes because I am demonstrating how to use this technology I've added this wonderful little list of two dudes the most complicated demo method whatever it works for my purposes so this is illicit siddhu's where I can easily just click and toggle whether things are completed or not if you actually refresh you can see the default state is that I have gotten the milk but I have not yet made the YouTube video that's this YouTube video a little bit of a meta joke then I gotta write the blog post but you don't really need to see a video of you writing a blog post that doesn't make any sense well this looks like in code is I have the list of to do is here just in a local variable I've added it to my initial state which is what's being added to my reducer used to my reducer is a wrapper for use reducer so effectively this is use reducer can't check the previous video and then I'm taking that state destructuring it getting to dues and then I have all of it at the bottom here this new to-do page component that I've made and what I'm passing it down to it is the array of to do's and the dispatch function and then in to do page I have right here taking those two arguments and then taking those to do is mapping them over or making to do items so each one of these things is a to-do item where I'm passing in the dispatch function and just copying over that item to each to-do item then here I'm H item I'm reading the title I'm learning whether it's completed or not with this checked and then on change I'm leveraging my existing use reducer architecture where I need a new action type called toggle to do complete and I'm just passing the title so that all these child components can do is just dispatch that one action to actually have that state be updated all the way up in the top of my reducer so if I actually go here I'm gonna go to the top I can see where this is being handled I'm looking through that array up to do is to find the item whose title matches the payload that's what I passed on there to actually find it should do that I want to edit and then I'm just toggling it just toggling it just so you can see that it's completed or not completed have gotten milk it's very important a young son is tricking a lot of milk does the bones good so I want to add one more feature with you right now and show you why context is going to be the great Savior that this video was created to demonstrate so I'm going to do is what I want to do is that if someone is not logged in so I'm not currently logged in I want to actually show an alert when somebody tries to click on to do this asking them to log in and not let them actually change the state of that to-do item so I'm gonna take this is logged in this is the normal way that you do this with props the terminology that people have used in the past Ernest is props drilling where you just kind of have a parent component that has a value in state and you should have to kind of drill it down through all the layers those components so that you can actually use it where you want it to do that's what I'm doing now passing it to the to-do page grabbing it here then again copying it over here and nothing to note here is that the to-do page does not care about this patch or is logged in but it has to have that to pass to-do item it's this intermediary component that should have no business doing about these values and real application code your layers gonna be much deeper than just three I have just the app that's a new page and astute item it gets way deeper so I can only imagine the pain you felt trying to those props all the way through those layers then here I'm going to take is logged in and I'm gonna have on click where if somebody clicks on this if it is if the user is not logged in I'm going to say please log in to click this and then here I'm going to do is I'm only gonna allow you to dispatch that value if you are logged in and make this a non there you go so now when I go over here and click this please welcome to click this and it's not changed that's cool I had a functionality that wasn't too hard to do but again the to-do item has no business knowing about dispatching is logged in no business at all so let's use context to make this easier the first way that you create a context is via a API I'll call this demo context react dot create context how lovely the function takes one argument is the default value for now I'm going to actually leave that no because I'll set that later and then on this object there's actually two properties on here there is demo context provider and demo context consumer provider is what provides the values for a context and the consumer is what then can consume those values in some ways it's like a portal where you can have some value from the provider get consumed by any child consumer so this looks like an actual action is I have to create I have to actually add the provider in my tree so to do that a new demo context type provider close that I'm gonna wrap my entire app around in that and provider takes in one crop called value this is the value that any consumer will get so for now I'm going to do eight naive implementation and I'm going to talk about why that's bad later so now you can take in anything for now I'm just gonna have it take in all of state and dispatch as an object again this is bad but I'll talk about why it later I'm just doing this for example purposes so then there are actually three ways so there's only one way that you can provide context via this way there are three ways to consume context for this video I'm only gonna show you the Hookes way because I am mostly focusing on hooks nowadays so I just want to show you how you would do this with hooks what you can do here is import the use context hook on a copy and then what I can do is go in like to do item which is where I actually want these two values and what I can do is get off the state and dispatch from that object and call use context won't use context requires you to give is that entire context object the provider and consumer contained it's kind of a point of reference for react to note would actually look up those contexts values so this is demo context and now what I can do is delete this dispatch is logged in and I'm gonna have this be is logged in just to have that be the same API save that and now if I click this still working so now if I log in my Harry password I took this things are working as before which means that I can actually go here sleep dispatch is logged in so I don't care about it here and I can also go up here delete it from here as well that's context that is using context that is the entire thing the the raw implementation if you were just this right now you'd be fine to the most part I know our house to do this props drilling or passing data to the intermediary component which does not care about those two values and also due to the strength of use reducer passing down dispatch I can easily allow any child component to modify the parents state by a dispatch having that very clear API of saying this is what I want you to do and not really caring how it happens rather than having to pass down these Multipla tune of callbacks where if I wanted to instead have a custom toggle completed function which I then wrap dispatch with like I don't need to do that I can just pass down dispatch and that already is the callback already so why would anything have a wrapper for that now let me talk about the gotcha with this so the way that context 3 that a context provider and context consumer works is that when you provide context or fronting a value any consumer then is subscribing this is subscribing to that provider such that if the providers value changes then this component will be we rendered without you data the problem here is that I actually made an inline object which means that anytime login using this parent component re-renders it's going to make a new object instance reactors just doing a very like is this the same object and if it's not it's gonna cause all consumers to re-render it which is not what we want we only want consumers to rerender when these values inside of that object change so there's two ways in you to solve this one I could use to use memo so I could say context value equals use amo which is another react which lets you easily memorize data so I can say we have to use memo use memo take some one function and I'm gonna have it return back this object context value and the second argument that's the to represent parens I'm actually returning the actual object the second argument of use memo is the dependency erase similar to use effect where if those values changed then I'll rerender that I'll remember how we compute the value so this still works this is fine I'm actually going to just make this be true so I want to keep logging in cheating really care this still works fine this is fine but actually what the react team recommends themselves is to actually use two contexts providers which is a perfectly fine solution so instead of doing this for I'm going to do is I'm going to have a state context and I'm gonna have a dispatch context so dispatch context I'm gonna put here and this value is just going to be dispatch I'm also gonna have the state contacts provider and this is going to be a value equals state put that in here and then what I can do here I'm gonna expand these out this is gonna be dispatch this is going to be the dispatch context and this is going to be my lovely little state context so let's say that you're freshers everything's working fine and the reason why the react team recommends this is that now different components might have different needs there might be a child component that only cares about updating state so I can just subscribe to the dispatch value so it'll never it won't be affected when the state value changes likewise the inverse like I might be a component that which is which would let me pause there was I gonna repeat that I might have one component one child component that only cares about updating state it doesn't care if the state value changes it's just wants to update state and just wants access to the dispatch function the state value is gonna update far more frequently than the dispatch function in point of fact that this hash function will never change that it will never have to rerender and by just divorcing these two values you've now optimized your application to not have to worry about unnecessary a tree renders because of conflated values on a content provider hopefully that makes sense they've also recommend even make a custom wrapper so I kind of tried a better API for this if you wanted to but I'm not gonna go into that right now and that's how to use context with immer inside of use reducer you have these three very powerful technologies that will make architecting and implementing applications from any size a lot easier to do from small toy projects like this one that I showed you today to large full-scale production ready business hardened tried and true very skilled bull big scale web scale applications I read that in a blog somewhere hopefully you'll learn something today context is great you can reach for it when you want to and need to don't need to if you don't have to it's there if you want to that made sense it's a lot easier to use nowadays and especially with hooks consuming that content is even easier than before I'm curious if you have used context in the past the old API News API is how you have enjoyed or disliked it very furious to hear your thoughts again if you're not already a subscriber becomes throw down below it's going to be fun patreon supporter or a patreon supporter and it'll be a back again next week with a new video for your eyes ears mouth and throat that's a weird way that and hope you enjoyed again soon bye
Info
Channel: Harry Wolff
Views: 31,164
Rating: undefined out of 5
Keywords: react, hooks, usecontext, context, usedispatcher
Id: StABs9JxeNE
Channel Id: undefined
Length: 17min 20sec (1040 seconds)
Published: Mon May 20 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.