Intro to React Context API with Phillip Troutman | JavaScriptLA

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
so before we get started I just wanted to get a quick sense of the rooms experience in a few of these technologies that we're gonna be talking about today just by a show of hands I'm sure most of you probably have SCI know a lot of you are actually current students or residents here at learning fuse but just a quick show of hands who here's has any experience in developing in react okay cool so a good amount how about Redux who has some experience in Redux well the exact same amount of people interesting awesome okay that's good how about see how many hands come up on who's here has ever actually used the context API alone by itself in an application that's exactly what I'd like to see cool so then nobody can call me out on anything that I say wrong tonight perfect like being the most experienced one in the room so undoubtedly you guys are all here to learn a little bit more about the context API this mysterious new buzzing technology that's kind of come out oh really big over the last six months to a year or so and undoubtedly to kind of answer this question right is it a replacement for Redux can it be a replacement for Redux are the rumors true did it come out and is it really gonna be the Redux killer that everybody talked about when in before it actually came out so my goal before the end of tonight over the next 45 minutes or so is to give you guys that knowledge to answer that question yourself is the context API the Redux killer that everybody talked about and also the tools necessary for you to to implements the context API any of any of your future projects and figuring out really when it's important or when it's applicable to add it into your your applications so before we get into the actual presentation a little bit about me this is always like the most awkward part of any presentation that I give is talking about myself so we're gonna do it really quickly like Vijay said my name is Philipp Troutman I'm a full-stack JavaScript developer usually working out of LA but the startup that I currently work for us also working out of New York called CS labs we build an online platform for JavaScript engineers to learn more whether you're an intermediate or complete beginner to JavaScript just upping your skills as a JavaScript developer in meantime aside from just regular work a lot of my open source projects or open source time has been contributed to this react context API developer tool for Google Chrome and I promise I don't want to mean make this sound pitchy or anything like that I'm not trying to get github stars from anybody or anything weird I just throw that out there in case anybody has any questions on it I know a lot of the seniors in the program right now are going through like your production project phases or juniors moving into your senior portion of the projects if you guys have any ideas or want to bounce any ideas off me I'm all ears after we're finished so what are we actually gonna be talking about over the next 45 minutes to an hour I've broken it down into four main categories of what we're gonna discuss first we're gonna talk about the origin of the context API you know where did it come from when did it come out a lot of you may be surprised to hear that the context API is nothing new it's actually been around for quite a while now just not really in its current form so we're gonna talk a little bit about where it came from and how long it's been around and then we're gonna transition over to where is the context API now how is it evolved and how is it transitioned from that starting point to what it looks like now in our applications and then we're gonna move into like the real the real like meat and potatoes of the talk does anybody use that term meat and potatoes I always feel like there's somebody that Snickers and they laughs at that you use in the back what's your name Cody you're my favorite person right now in the room meat and potatoes alright so we're gonna get into the meat and potatoes now I'm saying it too often I've I mean it's mean it doesn't mean much anymore we're gonna get to the meat and potatoes of the talk when we talk about the implementation patterns of the context API and how we can actually implement it into our projects and then finally we'll dig into that burning question that everybody has and I'm sure it's exactly why all of you are here which is can we replace redux with the context API is it possible and if so how do we actually do it so let's go ahead and get right into it the origin of the context API for those of you that are familiar with react this may be kind of second nature but for those of you that are not extremely experienced react maybe you don't know but the context API is simply a react API it's part of the react library which means that if you've ever implemented or imported the react library into any of your programs over the last however many years you've actually had access to the context API with just a few lines of code you could have had the context API running in your application it's been around since 2013 like I said before it's nothing new there's been a lot of buzz about it recently and we'll talk about why that is but the context API has been around ever since react was open-source back in 2013 and for anybody who's known this stuff and still kind of avoided it and kind of went with Redux because it was the standard and maybe you're like oh well I know Redux already you know it's not broken why fix it I don't want to learn something new it sounds really complex and hard the context API is really really simple actually in fact it's only designed to do one thing since it's been created and it's been part of the react library it's been designed to do just one thing and that one thing is to alleviate prop drilling who knows what prop drilling is who can give me like the it doesn't be like the Webster's dictionary version of it just in your own words somebody explained for me what is prop drilling Cody you want to since you're my favorite person right now yeah give you a properly to pass props and that it's down for function to function deeper exactly yeah hit it right on the right on the head to kind of give a did you just give me like did you give me finger guns dude you're you're pulling out a head as my favorite person because those are like my two favorite things is finger guns and meat and potatoes I couldn't have planted a better person in the audience right now no but absolutely Cody you're absolutely right it's it's that process of passing data down throughout your application throughout your react application through different components and to kind of give us a visual representation for anybody who's not extremely familiar with using react without redux or any other type of state management libraries it would be something kind of like this as a general outline you know we have our basic react application we usually have our data or our state stored at one of the higher level components in the app and if we had our children components way down here at the bottom that relied on that data up at the top we would have to do this thing called prop drilling where we would have to write code they would take that data from way up there at the top and pass it down every single level until we got down to our children components so we would write the logic to pull the data from our state into this component via props then we would go into these components and we'd write the logic to pull this data down via props from there and then we would write the logic to pull them down into the children components and then we'd have to write the logic to actually use that data that's stored inside the props and just explaining that it is a pain in the ass it's it's it's it makes me tired just thinking about it right so this idea of the context API is to take this super complex prop drilling and in unnecessary passing of data through these components that don't even need the data so essentially we're just convoluting these components now making our code heavier because we have more code to compile making our code harder to read which is in turn making it less maintainable we're taking all this data and passing it down the context API says not forget that we're gonna take that data and we're gonna and just pass it directly into whatever components actually need it without having to pass all these things down it allows us to be able to inject that at any level in our react API or in our in our reacts application at any point in time and again this is just a couple levels deep imagine how big of a pain in the asset is if you have 50 components or a hundred components or a hundred thousand whatever it may be it gets to be very cumbersome very quickly so this is what the react or rather the context API was designed to do but there's one big problem with the context API at this point the context API sucks it's terrible and some of you guys I can see your faces already you're like well wait this talk just took a really weird turn the contacts API really said don't just take my word for it if you really dig in to the react Docs you'll find these warnings everywhere context is an advanced experimental feature don't use content context just to avoid passing props there's an actual article that says why not to use context and then my favorite is just as global variables are best avoided when writing clear code you should avoid using context in most cases this is the react library that's bashing its own API so it doesn't necessarily instill a whole lot of confidence in this API right so again this is 2013 when the context API and react first became open-source now fast forward well rather just again to demonstrate what I mean by this is we had that context there was that idea of the context API that can inject data at any level that now is kind of rendered moot right we can't really use it in its current form so in enters our pal redux and 2015 now Redux came in as this state management library titan for react it quickly became one of the most popular react libraries for state management and essentially what it did is it took that context API that broken beat-up context API that react just kept talking crap about and it filled all those holes it's moved off those edges and allowed it and allowed developers to actually use it via redux a lot of people that are experienced in redux really understand that under the hood Redux just uses the context API now of course it comes with a slew of other features in Redux for state management but on the whole that's the big benefit of using Redux arguably is the fact that you can pass props and pass State and methods and things like that from a centralized store for your application at any point in your react application so where we had this failed attempt at the context API Redux came in use the context API and made it possible to pass data down throughout our entire application so now at this point most people are asking why okay so why are we having this discussion why are we having this debate about whether or not the context API is gonna be the redux killer because realistically it kind of seems like it was the other way around when it first came out right it seemed like Redux kind of came along and killed the context API and replaced that so why are we having this discussion why is there so much debate online right now on medium or on reddit or whatever it is or discord channels or or slack channels about which one is better to use well the answer to all those wise comes in the form of react 16.3 react 16.3 came out in March of this year and with that came this very exciting thing the very first pull request the very first merge request for this new version of context rather this new version of react was new version of context it was this completely revamped version of the context API which allowed us to actually do what the context API set out for us to do in the first place it allowed us to actually take that data from the top level component with no outside libraries no redux no mob X no anything else and actually just use react to pass that data down with nothing else so that kind of takes us through like our first foundational steps for the context API it takes us through how it started and now it was kind of a failed attempt and then Redux came along and kind of put it on its shoulders and allowed it to work and then context came back and said you know I don't need you and came out with a new version and now we have this workable version of the context API so now we have these two battling kind of technologies for state management in react so now let's let's move into my favorite part Cody what's my favorite part which is what I always refer to as the meat and potatoes thanks Cody yeah that's the one you just drop down a level man now the only thing that's holding you up top is the finger guns you got to step it up so now we're going to talk about the implementation patterns now we have that general foundation of knowledge for the context API and redux so on and so forth now we want to know how do we make this work now in our applications how can we use this to improve and make our applications more efficient and clean and more manageable which brings us into implementation patterns now one of the most powerful things about the context API is that it's so damn flexible on implementation you can do it in so many different ways there's so many different techniques to implement the API into your application we're gonna go over four of them realistically we're gonna go over this basic implementation so using these things called provider consumers and a very basic implementation how we pass data from one area of our application all the way down through all these middlemen components over them without prop drilling and how we access that data further down in our app then we're gonna talk about this thing called a default value in the context API and how we can use this to make our application even more dynamic then we're gonna talk about this really cool thing this technique using two providers in one component and don't worry I'm gonna talk more in depth about what providers are and what consumers aren't things like that but use to providers inside one component essentially taking data from two different parts of our application two different context instances and using that data inside one component in an effective way and then finally we're gonna take on together as a team we're gonna figure out whether or not we can actually create this thing called a central or for our application and for all of our redux users in the room this will become very familiar to you because that's essentially what Redux is all about it's about using this idea of gathering all of our applications state and all the methods and functions that can change that state into one location and making all of that stuff available to you at any point in our application we're gonna see if we can do that with just the context API but before we can do any of that we need to talk about the fundamentals of a context API remember I said that it's really the API is kind of simple I mean I know Italy only has like one one goal right is to alleviate prop drilling well it's also really simple because it really only comes in three pieces and if you can understand these three pieces these three building blocks you can use these building blocks to put together and different and interesting ways that makes it really powerful in your application so those three building blocks this is where we're actually going to have code on the screen so again anybody that's in the back that feels like you need to move forward at all please feel free to do so the three building blocks that we have for our context API is the context instance itself the provider and the consumer and that's it and if you can internalize those and understand how those are working together you can do a ton of different things in your application as we kind of explore these different implementation patterns and strategies so first let's talk about the context instance itself so the context instance itself is just this object this object that has these really useful properties on it this is our context API at work we create this object by simply defining a variable and setting it equal to the evaluated result of react dot create context react being our actual react library so it's just a method on the react library that we use to create this object and this object has a couple of methods on it or properties on it it has a provider property and it has a consumer property so we create our context objects and then we have access to two other blocks first let's talk about the provider the provider sorry you guys are letting me slip I'm walking too far over I can see if EJ getting mad at me the provider is simply a JSX component that we can use to pass value into our context instance and this is an example of just like a basic context instance so we created the my first context context instance that objects and then we use the provider property on my first context which is the object we created and we wrap it in a JSX tag and at that point we can wrap stuff in this JSX tag essentially saying that anything that's wrapped in this JSX tag anything below it we will have access to the value that we give to that context instance and that'll make more sense as we go through the rest of these so here we're taking this provider tag and we're gonna wrap some stuff and we want anything that we wrap in this provider tag to have access to whatever we pass in here to this value property this is the big important thing for the provider a building block sort of speak right here we're just passing in a string that says some data so we're saying that anything that we wrap in this provider tag is going to have access to some data via the third building block which is our consumer so we have context we have the provider and we have the consumer can you guys I'll see you back there well the consumer down here at the bottom cool so we have our consumer here now our consumer is very similar in the sense that it's used as a JSX tag it's you know put set up as a JSX tag and it's around something and this JSX tag this consumer has to return a function and this function under the hood is automatically passed an argument and we can set it up as a parameter whatever we want to call it for this example I just call it context value but automatically under the hood the value that we passed in here to our provider is sent to our consumer into this parameter here which then allows us to do whatever we whatever the hell we want to do with whatever value we passed in here so in this example I'm just doing something really simple I don't know if you guys can see that or not I'm returning a div from this component and inside this div I just have a simple sentence it says I'm the context value and then I'm rendering the evaluated result of this argument that was passed in here so when this is rendered to the actual screen onto our Dom we would see on the context value some data and it's as simple as that if you can grasp these three building blocks you have the context API now it's just about how creative you can get with building out the rest of your application and we'll should see some of those popular implementations in just a second but before we get into that I just want to get a quick judgment on the room thumbs I don't know if could you guys do thumbs here at learning fuse ever you do now you do is that what someone said thumbs on whether or not we understand so far the three basic properties are the three basic building blocks of the context API I'm good I understand I'm ready to see the meat and potatoes I have some clarifications that I can kind of put into a question and actually ask you Philip I have no idea what's going on I didn't even mean to come to this meetup I should have stayed home today everybody thumbs out on how we feel so far on these three building blocks we have a couple it's it's okay to have clarifying questions because I went through this very quickly and some of you are like 40 feet away and I can still hear myself in my left ear so when we start with you boss you have a very fun question yeah maybe you would get to it on that night now it seems to be missing kissed me that how the bow you with some Kayla get harder to pass down too okay so how your question is kind of like how does this data actually make it here okay well if we really wanted to dive deep on it it's gonna take some time essentially the quick and skinny answer to your question is that the context API takes care of that under the hood because it's utilizing some different properties behind the scenes on this context object to pass that value down you'll see some examples on on this actually working we're not gonna get too in-depth on how it's working under the hood though because it's gonna take us way past our our kind of time limit but if you do have more questions on it after this that you want to meet up with me and talk to me about it well we can dig into it a little bit deeper okay I know we had a couple more in the back whoo yeah go ahead either of you you guys are both in the same direction [Music] so just make sure I understand the question right so if you take this provider wrap a parent component let's just say say for sake of ease you wrap the in you wrap the top component you wrap app right can you have access to this a thousand components deep absolutely that's exactly what we're trying to do with it absolutely yes yeah you in the butt in the back boss great question so this stop props out children I kind of come to this a little bit later and I tend not to hit on it just yet because when you don't have it when you don't have it in context which is not saying context API I've been trying to avoid using the word context like have you guys ever tried to explain the work the key word this to somebody and you continuously say this it's a nightmare right I don't know how to do it without actually saying the word context but it's kind of out of context on how to use this at this point because we don't actually have anything to wrap with it you don't actually see it in in play but essentially what this is doing is you're telling react if I'm gonna explain it in a very crude way you're telling react that I'm gonna use these tags to wrap something and anything that I wrap in this this is how we get the the functionality that anything that we wrap in this will have access with the consumer for that value we're passing in and that'll make a little bit more sense as we see some examples coming up in just a little bit I'm sorry yes yes any children of the provider kittens and absolutely exactly right yep yeah by subject the provider section instead of value exactly and remember how I said that under the hood read UPS functions by using the context API that's exactly where you see it where you see the provider being passed in as a store it's very similar [Music] it's catching on [Music] you're getting ahead of me what's your name us Billy Billy you're you're creeping up there on Coby guy yeah no no yeah he's getting the finger guns too oh boy yeah no absolutely you're you're kind of stealing the thunder from our central store implementation so we'll come to that just a little bit but you're you're definitely on the right track yeah any other questions yeah Oh hmm oh [Music] one more time okay so you wrap the provider around a component and then try to use a consumer when it's not a direct descendant of yeah yeah um would you get it what you would definitely get an error I don't know exactly what it would be it would probably be something something is undefined at a certain point I have to really experiment I didn't catch that last part you just put when when you're building or where you're rendering yeah is that the question it's a really good question I've never ran into the issue I would say try it out yeah I would say honestly because I don't think I've ever ran into that issue myself so I'm not sure where it would catch the error I would have to actually go in and do it in order to figure it out so I would say experiments with it it's the best way to kind of figure these things out anyways it's just to experiment with it yeah cool good question huh any other questions before we move on to the real meeting potatoes yeah yeah yeah yeah it has to be Val you know we just be that one instance of value and then you can add anything that you want into value cool right on no problem all right cool let's um let's get into our implementation patterns so yeah that's nice got some excitement in there cool that's a that's a good sign right alright so this is the part that I kind of struggled with when putting this curriculum together to explain the context API because I always hate getting lectures from people are going to workshops or meetups or anything like that and it's super heavy into code like obviously you know everybody wants to see a certain amount of code but I hate when somebody uses just code to explain a concept it's it's really hard to follow especially when you're 60 feet away and you're staring at code that you've never seen before and you're trying to learn something new so I also wanted to kind of incorporate more of like a real-world example and like kind of a visual on these different implementation patterns so for the next three of our for implementation patterns we're gonna use a similar example to kind of see the differences on the implementation strategy so for our example I wanted to use something that's very close to my heart something that I'm very passionate about and I hope that you guys can relate to it as well we're gonna use the idea of ordering pizza because pizza is probably by far my favorite food so I was really excited to come in today and see that there was actually pizza here and I think it's actually from Domino's which is my favorite piece no it's not is it Pizza Hut well they have the best breadsticks Oh I mean you know beggars can't be choosers so we're gonna use the example of me ordering pizza to demonstrate this setup of the context API so let's kind of break down this this the silly diagram a little bit and talk about how this relates to code because we have we have Domino's which is my favorite pizza place by by all means it's the best pizza place out there anybody that wants to disagree with me we can talk after to really settle this but Domino's as my favorite pizza place and I frequently order pizza from dominos I love how V J's like oh I got to get a picture of this setup thanks for that VJ yeah make sure you tag my head down here yeah so let's break down how this relates to our code and the context API so we have Domino's as our representation of our context instance so remember throughout these these examples that we have three building blocks for setting up our context system right so our first one is our context instance which is going to be represented by our Domino's restaurant emblem whatever you want to call it and every context instance or Domino's has its own delivery system or delivery person aka our context provider right and every provider is past something it's passed some data or in our silly example we're passing our provider a pizza it's gonna ultimately be transported to our consumer which is hungry Phillip hungry me down here ordering pizza ok is this an okay is this everybody is resonating with this example very much I can see everybody laughing at it yeah well we'll talk about some some different strategies to explain this later if you guys got some good ideas all right so we have me representing the consumer for this data right and since I'm such a valued customer at Domino's I order from them so often even if their delivery person is super busy and there's like one two or even three deliveries ahead of me that pizza is still coming to me first they're not going to go through this first second and third delivery these deliveries are representing our intermediary react components that don't need this data that don't need the Pizza our providers not going to go through them not gonna prop drill through them it's gonna go directly to me down here so let's see what this would look like in some actual code are you guys good with you guys can see it from back there still cool all right so we have our three parts we have our three parts of our context system our contacts API setup right our first part is our context instance itself so if you guys can see up here we're setting it up on line one I don't know if you can actually see those numbers over there but we're setting up our Domino's context instance we're saying Domino's is equal to react create context which is setting up our instance and then we have our number two part which is our provider and you can see we're doing that right here we're saying Domino's dot provider Domino's being our context instance and we're using the provider property on that objects and we're wrapping it in outer div and for this example outer div is our highest component in this application right and it kind of goes back to some of the questions before with this this dot props at children we're wrapping this outer div essentially making available this value here pizza the string pizza making it available to any component that is at this component level or below so essentially our entire application so we have another intermediary component that's here that we're not doing anything with we're not prop drilling through and then finally we have our bottom component or inner div component an inner inner div component we want to use the value that we gave to our provider that's string pizza so we do that by using our Domino's dot consumer so we we do Domino's dot consumer and we know that from that has to return a function so that's what we have going on here we just have this anonymous arrow function and we know that under the hood the context API is going to pass this value pizza into this parameter here and then we can use that value however we see fit so here we're gonna return a simple div with the value of Domino's value so if we were to actually compile this and render this to our Dom we would see a simple div and inside that div would be the words pizza and that's it it's as simple as that so that's our most basic setup for the context API our most basic implementation of it so let's see if we can get a little bit more creative let's see what happens when we try to use to providers inside one component so taking data from two different providers and using it inside the same react component so of course we're gonna bring back our pizza example but this time we're gonna add something to it because I have this really weird problem whenever I want to eat pizza because my favorite pizza comes from Domino's Bar None we've already discussed this but my favorite breadsticks comes from pizza so I always have this really weird situation that whenever I want to eat these two items I have to make two separate orders from two different restaurants and have them deliver to me so again very similarly we have our context instance but not just one but now we have two different context instances right we have Domino's and then we have Pizza Hut each of which has their own delivery system their own providers which is our two delivery people here they're both being passed data you know this guy's being passed the the provider for Domino's is being passed a pizza and the provider for Pizza Hut is being passed our breadsticks and again because I'm such a valued customer at both of these establishments they don't care about these other deliveries that are ahead of me they take that data they take that food straight to Philips house right straight to the consumer so again let's see how this looks when we actually put it into code so a little bit more code here because we're dealing with two different context instances but still the same basic premise we're still only using three different pieces to the context API structure what was that what's the first piece of our structure piece number one who are members what is it not that's not that's not piece number one the context instance right so we have to build our context instances so on lines one and two if you can see it we're building a Domino's instance and we're building a Pizza Hut instance so that's step number one what's step number two the provider exactly thank you yeah it's our provider and as you see we have to get a little bit more creative with our provider here we're using two of them but it's still again the same basic premise we have our Domino's provider here being passed the value of pizza and we're simply nesting our next provider within it so we nest Pizza Hut dot provider not passing it the value of breadsticks and we're still wrapping my div which in this example my div is like our top component right now for our application essentially allowing this data this values to be passed to any component thereafter my div so we move down here and what's our third piece to that context set up consumer exactly so again it gets a little bit more complicated because now we're dealing with two of them but they're still essentially set up the exact same way down here we have our Domino's dot consumer which is returning a function and that function is automatically being passed the value from the Domino's provider which is pizza and then it immediately returns the pizza hutt dot consumer which returns a function and that function automatically gets the Pizza Hut value that was passed in up here breadstix so now from within this component we can return and use that data that data that's being passed through the context instances so here we're just rendering out a div that has both pieces of data in it so on our screen if we were to render this we would see a div with the word pizza in it and the word breadsticks in it so you can see with just knowing those three components we start to get much more flexible with how we implement it into our applications which becomes a huge benefit later on so we're halfway through our implementations do we have any questions so far let's get thumbs on just these first two implementations the basic implementation and two providers within one component we're good to move on to the rest of the meat and potatoes have a couple of clarifying questions so far I'm still lost in figuring out those three basic components to context how about you Boston we have a question right there yeah the second provider being pizza it can be separate to the outside of that it all again it all depends on what you're trying to accomplish in your application for this example since we're trying to pull in that data into one component I mean it could be nested deeper in the application structure as long as it's still a parent of where it's eventually going to be used later on down in the application that's a really good question a very good thing to point out absolutely returned out of the Dominos provider I can't even see the lines myself line 14 here yeah so consumer if you're gonna use it in this example in regards to the consumers his question is more I think about the providers and the consumers yeah you would have to Ness these because you're trying to render out for this example a div with both of those things in it with both of those pieces of value in it you would need to nest them if you're just trying to use the pizza then you don't even need to use the Domino's consumer down here yeah you just use the pizza at one you still have access to it because it's still ultimately a child of where you set up your provider yeah and I know you got another one back there great question why you would want to use two different like why not just use it in the same provider right if you're just using the same data I haven't seen too many instances and I haven't actually used it too much using two providers for one consumer with the exception of using context instances to pass down Styles like for instance if I have two different styles like I have a light theme and I have a dark theme and I'm trying to pass those down independently somehow and we'll also talk about that when we get to the default value on the next implementation it's very similar why you would want to even consider using this implementation more so just like separating separating your data and more manageable pieces or maybe you have in one context instance you're storing all of your your data specifically like data that you want to render to the screen whereas in one context instance you want to store all of your styles so you can use one context instance the style of div and then use the other context instance to fill that div with specific text or something like that yeah exactly exactly yeah there's no performance hindrances at all with this again it just becomes more so what are you trying to accomplish how many different people are really working on this is it going to confuse people having it in two different places versus one place you have complete flexibility with the context API which is one of the key differences that we're gonna talk about when we start comparing this with redux yeah and one more you need to in sport provider great question do you need to import the provider the provider good question the provider no you do not need to import the provider you have to imports let's see here you would have to import the consumer at the very least to utilize the consumer within that component yeah but it would still under the hood have access through the context object to the provider value so you would have to import the consumer for this example if you have these separated and module lies in two different files I'm not really sure I follow the logic of it just because it's it's it sounds a little bit specific let's let's talk afterwards and then we'll talk about the the details of it yeah I definitely was there anymore sorry I went an extra slide bag any more questions before we move on to the other two we're good all right cool let's move on to the next couple of implementation patterns so let's talk about default values and this is the last one I promise that I'm gonna use this example but we're still gonna use Pizza as in a visual example on how this works so using something called a default value in the context API just adds another layer of flexibility in our implementation so again we have a very similar set up to eating that we did on the very basic implementation where we have just one context instance one provider here our delivery person this delivery person is being passed this pizza and then it's delivering it down to our consumer again not having to prop drill through these intermediary components slash other deliveries that are ahead of me right but at this point you're probably wondering like wait hold on a second Phillip there's something here that wasn't here before like you're not gonna sneak that sketchy-looking salad that's just kind of lingering up there near a context instance through without explaining that so what is this salad actually doing here well I set up this context instance or this context set up in a slightly different way I set it up so that for whatever reason for whatever reason we don't have a delivery person we don't have a provider and the provider obviously won't be receiving any type of data or pizza if we were to just get rid of that altogether the default value that our context API would send down to our consumer would be this sound which I know is just an equally amazing treat to be delivered to you as the pizza but it would defaults to this salad so let's see what that would look like in code so let's again let's break down our three points are three basic building blocks for our context API number one what's our first building block for the context API the context instance right so we're building that just like normal line one constant nose equals react out create context number two what's our second building block to our context API our provider right hmm well we don't have a provider right so what's the point of that how are we gonna possibly imagine that some data is gonna be coming down here to our consumer if we never setup a provider this is kind of a stupid example right Phillip well let's let's take a step past step two and we'll come back to that in a second but what's step three of our setup for our context instance the consumer right so we have our consumer thank God we set that up so we have our consumer set up just like normal our consumer is returning a function that function is automatically receiving some sort of value here right we have a parameter set up hopefully it receives something and then this my div component is rendering a div that has Domino's value being printed in it well well but what the hell is gonna come in here when we actually render this to our screen well the context API is gonna look for that provider right and it's gonna say there's no provider but the context API is smart enough that it knows when it doesn't see a provider anywhere between the context instance and the consumer it checks this little area right up here this little area is where we can set up a default value that says Hey look for my provider context API if you don't find it check the default value for any type of value that's there well that's exactly what the consumer that says hey give me my value from the provider oh there's nothing there check the default value hey there's salad there let's pass salad down into the Dominos value here if that provider was there if we did put that provider in the right spot like we normally do and surround it or wrapped my div it would simply take whatever value we pass to it there but when it's not there when there's an absence of the provider it checks our default value cool now that takes us through that takes us through kind of our our our really flexible implementation patterns and I just want to pause for a second take any other questions that we have because next we're gonna try to tackle this big question can we mimic or replace the functionality of our Redux store of our centralized store idea using the context API so real quickly before we move on to that does anybody have any questions on like the default value or any other lingering questions they may be kind of hanging out yeah yeah what would be a real yeah that's usually the question that we get on this this implementation pattern is why why would we set it up this way and the answer is very similar to like the other answer for why would you use to consumers in one component one rather why would you use to providers inside one component why not just combine the providers it really just comes down to segregating our data in a way that makes the most sense for our application so in this this kind of setup we can create one context instance we can wrap a certain part of our application with a provider for that context instance and pass it a value and then we could use this consumer in a different part of our application that's not a child or a descendant of where we use our original provider that seems a little bit hard to kind of follow and visualize but in that way we're using one context instance but we have two different sets of data that we can use in different parts of our application just depends on how want to set it up and what would be the best use case for our application that answer but yeah you got some questions yes to send down different values can you okay so can you use instead of using two providers to one consumer can you use one provider for to consumers so you are using the same like context anything you create two different providers to two different components two different providers being passed to different values sure yeah uh actually a few different components like they're not like imperative so they're separated they're not under like the same parent provider component yeah and that's essentially what we can do here with this context instance that we have we have it set up here with this default value yeah absolutely you can separate them so they're not actually under the same provider mm-hmm absolutely any other questions before we move on to tackle this big centralized store example which I promise is not going to include pizza or any food of any kind oh yeah see I need to figure out an example for how to how to bring that in yeah weird we're done with meat and potatoes and pizza and I didn't realize that there's a lot of food that's going on in my examples all right cool let's move on let's talk about it so this idea of creating a centralized store with the context API super powerful right because essentially what we'd be doing if we can accomplish this essentially what we would be doing is rendering the redux library useless for us so can we do it so we can that's it to not build it up for you guys too much and we do it through a couple of different steps I really need to work on my cliffhangers and my transitions as well for this we do this with a few different steps right I'm some of them are gonna be a little bit new a little bit different but ultimately it still boils down to using our three basic components for creating a context instance or a context setup so first thing we're gonna do is we're gonna actually create our context pretty simple we've done that a billion times already before we create a normal context instance but then we do something a little bit different we don't just go right ahead and declare a provider first we're gonna declare a class a new class and this class is going to return the context provider so just stay with me we're gonna we're gonna show some examples of that I don't have any fancy funny images but we're actually gonna see the code for how this would look in just a second so we create a class and that class is going to return the context provider and then we're gonna pass values to that provider just like we normally would so we can do something where we're not just passing a simple string we pass in something that's a little more interesting bless you I think you're welcome so we're gonna pass something a little bit more interesting to our value prop right now we're gonna pass it in objects and on that object we can store anything we want including state which is what we're going to do in this example the state for the class that we just created and we're gonna set up state just like we normally would in any other react component and then we're also gonna pass it some methods we're gonna pass it some functions that have the power to change this state in that class so we're gonna do some fancy binding like we normally do and then we're gonna pass that method on that value prop object then we're going to take that entire class that we created in step two and we're gonna wrap it and we're gonna wrap our top level component similar to how we've done in the past with our direct context op provider component so what does that look like so for this example we're gonna say that we're building out an application it's a like photo gallery right and we want to have nothing rendered to our screen at first but we do want to at some point be able to click a button and and send out some sort of Ajax request to an API somewhere bring in some photos store those photos in our state and then render that state those photos to our page that's generally what we're trying to do here with this application so how would that look so again following step one we're gonna create our context instance right so we create gallery context and that's equal to react create context simple easy peasy then we're gonna create our class for this example we're just going to call our class central store to be semantic about it right so we create a class called central store up here on line three I think that is and then we do our normal react stuff we'll come back to that in just a second but ultimately from this class the central store class we're gonna render our contact or gallery context dot provider remember gallery context is this context value that we created up here we're gonna return from that class gallery context dot provider and then we're gonna put some stuff in there that we'll talk about in just a second and then this comes back to the question that somebody had right in the beginning which is what is this this dot props dot children thing this is us again using that telling react it whatever we end up wrapping our central store in whatever we end up wrapping that around we're saying that we want all of its children it and all of its children down our application have access to whatever we're passing into this value property that's what we're doing here on the this stop props a children's section so we have the provider set up that we're returning out and then we're gonna pass some stuff into it so what are we gonna pass into it well first of all we're gonna pass our state into it we're gonna spread our state object into that value so we set up our state up here and very simple state we just have a property called images and it's just set to an empty array right now cuz we don't have anything set inside of it at this point again remember we're gonna fetch that data from somewhere else and bring those images in so we define a function called get photos and then we you know set up a simple fetch request to an API somewhere that's going to return those those those pictures and then we're gonna set our state with those images that are returned from that API and then we simply just bind our this this get photos to our state like we normally would in any other react application and then we take that get photos function and we set it on this object that we're putting into the value and essentially what we're doing here is we're setting up our application so that we will have access to the state of our application and any methods that can change that state at any point at any level in our application and then our last step our final step is simply taking central store which again was that class that we created up here we take central store and we wrap whatever our top component is you know convention is it is it's app or whatever we call it we wrap our top component in that central store and now we have access to everything that's in value throughout our entire application which means that if we call get photos at any point down further in our application we click a button whatever kind of event fires and we set or we run that function it's gonna fire it's gonna send off our our fetch request get that data back it's gonna update State which is gonna hit our diffing algorithm with reacts and it's gonna re render all the components that change which would in turn render all of our photos to our page so we did it we set up a centralized store yeah see we got some people that are site in the back that was I was pumped on this I was like hell yeah I hate Redux now right no not necessarily not necessarily we'll talk about that in just a second but essentially we just did it we recreated the general functionality of Redux and how we use it normally in our react applications without having to import any other libraries remember all of this stuff is native to react it's already there just waiting for you to use it so which brings us to that that burning question is the context API a replacement for redux now I'm sure most of you probably knew that you weren't gonna get a person that's gonna walk in today and tell you yes Redux is dead never use it again of course not everything has its own place so the real answer to this question is it all depends it all depends there really it all depends on what you're trying to accomplish it depends on your situation it'll bendlin a few different things so before we start you know wrapping up and taking any final questions that we may have let's talk about you know just high-level overview some of the key differences that'll kind of allow you to figure out early on whether or not you want to use the context API or redux in your applications before you actually start building them so what are some of the things that should roll through your head when making that decision so keep in mind as we compare these to the context API and redux context API is flexible very flexible as you've seen we just ran through four different implementations and that's I mean that's not even half I mean that's that's a fraction of what you can actually do with implementations of the context API whereas Redux is very opinionated it's very structured on how you have to set it up you have to have things set up in a very specific way in order to make it work now is that good or bad it all depends on what you're trying to do are you the only one that's working on this application is it going to be a small or medium sized application where you can really easily spin up an entire application with the context API in a very light manner because you're not pulling in any other libraries or anything like that if that's the case context API is looking pretty good at this because as you've already seen we just did everything that Redux basically does with the context API of course there's some key differences there like dev tools and things like that but we've done pretty much everything that we needed to do with the context API but do you have a bunch of people working on your application do you have a team of 20 engineers working on this huge application on a regular basis because having something that's super flexible may not be what you really want in an application like that because now at work when I first started my job where I'm at now we have tens of thousands of lines of code but we use a react Redux setup right we have we have reactant Redux in our stack and because I'm experience in Redux I was able to go in and say holy like this is huge like how do I even get around like my first assignment that I had to do I was like I have no idea how to get around in this codebase but I started digging into it and I know Redux well enough I was able to say okay well you know we have our our actions here and we have our our our these files are here and I was able to kind of dig and sift through all of these different reducers and things because I knew how redux operated and on a large scale you're still able to pick through and figure out what's happening in what files because you have a very opinionated library to work through you don't have that with the context API so it can be done a lot of different ways so it could be confusing the context API is included in the react library makes it a little bit more efficient a little bit lighter there's less code to work with you don't have to import anything whereas the redux library is an outside library that you have to import the react context API is minimal setup I know one of the key things that I hated when I first started using redux was all the damn boilerplate you have to setup who's with me most of us okay and everybody else that didn't raise your hand you're all damn liars I know you're lying to me right now I that's usually one of the biggest kind of learning curves with redux is learning how to set up the boilerplate for this but as you've seen so far we're all experts now in the context API right yeah absolutely in 45 minutes we just learned the context API and we can set that up really easily so there's also something to think about there and then probably one of the next big ones for deciding between the two of these is this version of the context API is a lot newer so it has a lot smaller ecosystem around it and one of the huge benefits of using Redux is that ecosystem mainly the developer tools for Redux are awesome you have time travel debugging and all kinds of really neat features that allow you to debug your applications much more easily so also something to take into account when deciding whether or not you want to use redux or the context api so what other questions do we have
Info
Channel: hackbuddy
Views: 10,146
Rating: 4.9236641 out of 5
Keywords: javascript, javascriptla, react, phillip troutman, react context api, react context, react meetup, codesmithio, advanced js tutorials, js tutorials, react vs mobx, redux vs mobx, redux, redux js tutorial, react 16.3, context api, mobx, redux react, flux react, react mobx, react state management, react application state, redux alternative, context api in react js, new context api, send props, context-api, context api tutorial
Id: u0slAvqjA6E
Channel Id: undefined
Length: 59min 29sec (3569 seconds)
Published: Mon Jul 16 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.