Context API in react | get the concept

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey there everyone AES here back again with another video and Welcome to our ongoing react series I hope you're enjoying this series because I'm enjoying it so much teaching this series uh first of all a very basic Target for you to hit that uh comment section uh we're expecting just 100 uh comments if you can uh that would be great uh so just hit that comment section first uh just do the comment some appreciation or maybe I'm just watching it on this date and let's continue the Journey of react and now we'll take takeover Journey now we are pretty much comfortable with the loops uh with the hooks uh pretty much looping the things variable fetch uh API fetching and all of these things uh it's time that we explore more advanced feature in the react now one of that feature is how do we handle the data now one of the primary job of the react is to handle the reactions and that's why we called it as react the reactions happens basically on two major factor the first one is the props and the second one is a state and you will be passing on this dat data into various of these component let me show you we have already seen that by creating a card component that you provide some data to that card component whether fetching it from an API or just generating the data however youve pass that data that data uh passing is very common let me show you one such example uh that is pretty common so let me share the screen first so this is the diagram let's just say this is our dashboard a main component and inside this we have divided the pages just like previously we have divided uh into navigation bar Footers and whatnot uh this time let's just say this is our home dashboard inside the dashboard there is some another second component then inside that there is one more component and finally this is the component which is showing some of the data like displaying how many people have watched your video and if you look at the current perspective this is very Troublesome because uh this inner component is actually called inside this component and this component is getting called inside this component and this component gets called called to this component right now we have no way absolute zero way that we can actually pass on data from this outer component to this component in order to do so that hey if I want to pass on this I have to first from this element or is this from this component I have to pass on data to this component this component will further on pass on data to this component and finally this component will pass on data to this component so you can see here that we are passing props into these component and all of this is not really bad but one thing that is bad here is this component is not using any data still it has to just access the data just to pass it on and for one level it's okay but if you can see here the moment it goes onto second level or third level you can see where the problem comes up some of the components which don't need this data also have to access this unnecessary data and based on this have to evaluate whether should I render reender and what not but they are not using this data ultimately this inner component is using that data so how can we resolve this problem this problem can be resolved by just one simple solution which is also termed known as State Management now there are lots of State Management libraries some are inbuilt into react some only one and there are other thirdparty libraries which you can study and we will study them so one uh easiest of the solution is let's just say we have this uh global variable uh that would be a good name and somehow we start a mechanism that if anybody wants to access the data all has to do every single time is just go up and ask this guy that hey I want to access this data if anybody else wants to access any data let's just say this element then he has to go and just go for this guy and ask data to this guy there is no other way if you want to update anything if you want to uh want to access any information you ask this guy if this is the central source of truth that's what it is happening here and this Global uh variable is known as a store in some languages or some Frameworks not languages in some Frameworks every single framework we call it as a different one the one that we are going to study is known as context API So This Global is known as context I'll show you more of that the idea is really simple we will have a separate strategy and the only thing is that all of these components are aware of this Global state that is all that that is all it is now this concept can be a little bit tricky to understand because of the code issues not the concept issue the concept is this much that we have a central place from where we can access the data whenever we want we can update any data in that Central repository from whatever the component we want this is the centralized concept but just because there are so many ways of writing this exact same code there are multiple iterations of that that makes people confused that okay what is the syntax so understanding the data data flow is easy but writing the syntax is a little bit tricky and that's why I'll walk you through with a couple of syntaxes so that you can know okay this one is exactly same this one is exactly same and this one is also exactly same so we'll be working on with that so I have a small flow diagram for you so what we'll be doing is we'll starting uh we'll start the project and we'll create a react app y v or whatever however we do that then we're going to create a context the context nothing this is the context this separate thing then we simply create a provide the context are also known as context provider what do I mean by context provider making sure that all of my components that I have is aware of it they are not going to be aware of them automatically there is a mechanism there is a flow of the data that hey all the components now are aware that there is a global state so that I can access my data so the next step is this one provide the context and the third step is consume it wherever you want however you want you just consume it so this is exactly what we are going to do in this video and in the next video itself I'll walk you through one more iteration of this exact same process but with a different minor tweaking in the code itself so you get the multiple idea of how the code is being written so we'll just close this one and we'll just get started with this one this is absolutely easy nothing to be worried I'll just open up my oh there's something already running all right so we'll close this and let's go ahead and start this one so this one will be our new project uh probably eight uh so we'll just call this one as create no not create my bad npm create V and we'll be going with the latest yep and we will be starting project name so this one is 08 and we are talking about mini context so let's just call this one as mini context context API that's exactly what we are studying and the best part about the context API is you don't need to install anything else that's the best part about it uh let me just dump this open this up in integrated terminal and we'll just say npm install should be fairly faster uh the best thing which I love about it is we don't need any third party resources the context API is directly cooked in inside the react it was not there in the earlier version but as the react evolved as a library it it got this one and then we can say npm run Dev that should be easy and this is how the basic looks like we won't be even installing anything into it no Tailwind nothing we just want to go absolute basics now first let's try to create a problem that is the major thing that how we are going to create this a problem first so let's just say inside the source we'll right click and we'll create a new folder first let's Place everything inside the components and this is a legit problem that we'll have and new file the first file is going to be simple login uh we won't be doing too much into the login so R fce react oh nothing oh my bad it should not be loging uh it should be login jsx rename login. jsx and now we can say RFC come on RF C there we go we can close this down so this one is not going to be too much of a problematic uh I'll just be writing the basic boilerplate code uh you can also write along with me that would be really really helpful so first of all what I'm trying to create this is a basic login so login has a username and a password it doesn't connect any with any data it's absolute basic raw one here so let's go ahead and say that I will have a username and that will be a set username by default it's empty we will also have a password field let's just say the password field nothing else it's not doing anything now uh once we have this we will we'll need that something that needs to handle that we'll obviously have a login field the password field and a button so let's just go ahead and call this one as handle submit that's okay for me and inside this we are not going to do anything so will just write empty slashes uh prevent the page from refreshing yeah whatever that is I'm not really bothered or much worried about this one in this one let's go ahead and add those fields so first of all we'll have a simple H2 which says login this is my login component so that I know and aware about it then we are going to have an input with the type of text text there we go uh we don't need this name or ID so I'll be just removing this and there we go let's move it to the next line we'll be adding couple of fields onto this one not too many just the basic however we do that all the time so on change is going to be uh first of all we need the value one but yeah on change is also good that at the time of changing this is the input field for username so let's go ahead and add the value as well that you get the value from the username once you have all of this let's also add a placeholder the value of username and what else I think that's it okay uh another input put field that we are going to need is first I'll add some of the spaces so line break there space and then we'll be having an input of type password there we go and there we go my bad what is happening there okay so this is input type password this one okay we don't need this ID or this stuff let's move it to the next line This one is also going to move the next line and again really basic first of all the value the value will be derived by password let me scroll this and then we have on change on change the value is going to be governed by the set password that we have let's add a placeholder and that will say password and after this we will be having a button let's add a simple Button as well button there we go this button is going to say simply submit and we'll be having an onclick event on this one since we didn't created any form so we're going to say onclick and on the on click this is handled by the handle submit so this kind of a component you have always built now we have a simple value how it is handling we'll talk about that first let's create what the problem what we have now similar to this component you will also be dealing with this in the real world application as well which is going to be profile profile if I can write that jsx and let's go out of CE very basic and in the profile all what I want to do is let's put a space is I want to display a username right now I don't have a username but somehow I want to display the username so how can I do it and I am pretty sure you are not understanding the gravity of the situation right now this is so much of a big problem and you might be saying hey what's the deal with that why is it so much of problematic I can go simply into my app.jsx or main. jsx or any place at all and I can just go ahead and load this up like for example in the app.jsx I can go and remove all of this content that I have so let's just go ahead and remove all of this and I can load these component here for example I'll just say H1 here and I'll say react course or react video would be good react video for context API and then here at this I can load the login component just like this and I can go ahead and load the user component not user profile profile here you go and the profile component is there any issue with that if I reload this there shouldn't be any issue let's go ahead and inspect this this should be loading up uh use state is not defined my bad uh we are using State here so this one is going to give us use State I don't like to edit out these problems because these problems are something which teach you stuff so as we can see there is nothing wrong with this one we are able to load this one now your first initial reaction would be that if I can load all of this probably I can just pass on data of the login and all in the app.js and from here I can pass on this but imagine the situation that from the profile this data actually goes to other third component which are loaded inside the profile just like here I can add more things just like I was able to load in my app.js this profile thing I can also go ahead and load more stuff so I can just go ahead and literally say uh more component so what's stopping you to have more component here uh maybe you are having a dashboard if I can write that component it's hard to type and talk at the same time so imagine that this is a dashboard on the dashboard you have left Pane and right pane you want to display the data on the right pan but right Pan Is Not Alone further that there is a top section and bottom section so two more two more component in the top section you want to display this data profile username but the top section is also composed of smaller components so how long you're going to be passing these components back and forth you get the idea now you get the point that we need some better solution and this is exactly why we have the solution up here that we want to create a simple Global state where we can add all of these thing and this is known as context in the context API and the context provider but in the case of Redux I I have that video as well we will be talking about that you'll find that video in the playlist as well so you can see that there we call it as store so call it store call it context the concept is exactly same we need a centralized repository centralized uh store where we can have all of this data this is exactly what we're doing so now it's time that we understand that how we can actually implement the context no extra Library needed the step one is to create a context and then to create a provider so first of all let's understand that how we create this context it's a simple step if you're taking the notes you can take them as well all right right so we'll come back onto these logins and profile in a minute first of all let's close this one inside this let's create a new folder and let's call this one as context creation of the context has two parts some people do that these two parts into separate files some people do that in one file doesn't really matter I'll walk you through with both scenarios first one here the basic the second one will be a little bit more advanced not Advanced but yeah easier so let's create a new file and first we're going to call this one as user context uh by the way you can have multiple contexts since this is not going to return any jsx I'll just call this one as just the JS now this context uh could be M for multiple reasons or multiple resources this one is for user context uh another thing could be for product uh context another thing could be tweets context so uh just like everything needs a context in the real world this is exactly where it comes from for example fan you don't understand anything with the fan it could be a ceiling fan it could be a table fan it could be a fan in terms of a Bollywood fan Hollywood fan a YouTuber's fan it has a context it needs a context that's exactly what we have so we're going to go ahead and say hey react let's come react and react uh directly gives you this context so all we have to do is user context react. create context just like you import use State and all of that we have the create context as well and after that you all you do is export user context so your question might be okay we have that empty repo the store which will be holding all of this related to the user but where is the data there is no data you are absolutely correct there is no data when you create the context that's the step one now once the context is created the step two is actually to create a provider or the context provider because right now it is not usable so something needs to uh be a central men which can allow me to access the data as well as feed the data ins in into that so let's go ahead right click and create a new file and we'll be calling this one as user Contex text uh provider and this one is actually jsx because this is a wrapper as I told you uh we need a wrapper this whole thing everybody should be aware of it the way how we do it in react is we create a wrapper just like for example in this case if I go into main. GSX you can see that this react strict mode is a wrapper for all of my component that I'm creating because the app further down the road app actually loads these guys so all these guys are actually also loading in the strict mode why just because of this one this one is wrapping the entire application so we need to create a context provider and we need to learn that how these sandwiching rule actually apply so it's actually not really that bad it's actually simple so we'll be having first let's just say react and we'll be using are we going to use uh use State probably not okay uh but we'll see that in a minute and we need to import the context that is the most important part so now you have access to the context which you just created and now we'll be using that so the first thing that we are going to do in this case is how to create this context uh we have this and this now let's go ahead and create the user context provider yeah that that's a good name user context provider this is nothing just a simple method just like that a simple arrow method just like that okay so far it's good now the next step is to export this so go ahead and Export default user content provider now this is where the functionality goes the first thing that you should know or you should be aware of this is that there will be more components which will be coming inside you just like we use the outlet yeah exactly same concept almost exactly so first thing is as a prop what you'll be getting you'll be getting children's so just write children if I can write that correct uh you have to actually return that children back but before that we need to actually say that what is the data that you'll be using or something like that so I'll be saying that hey I'm having a state so I'll be just calling this one as user and then I'll be having a set user this is right now an empty object that is also good but right now we don't have any users so rather having an empty object I'll just say null I have nothing as of now after that I'll just go ahead and use the return with the parenthesis and what I'll do is I'll be using this user uh context. provider and yes this is a syntax we cannot do anything for that come on user context do provider and this is how it looks like user context provider this is something which is given to you by default the moment you use the user context it automatically gives you the access to provider uh the reason for that is react gives us this create context the moment you have used this this was given to you by the react itself now inside this you actually do nothing and you just add a children this is the syntax but alone this is not useful because now now your entire application will be aware after 1 second we will use it exactly just like we use this strict mode we will be using it exactly almost that uh but right now it is having the access of it but the reason why we created this user state so that this data should be accessible to all the children that's the goal if you have more data add more things here add more calculation maybe you want to have a fetch request and whatever comes back from the fetch you want to give the access of it to all the cont all the components you do exactly like this but right now I have a variable which through which I can access the data I have a method through which I can set any data into this user so I have access to all of this now I want to pass on this so the way how you do it is simply add a value and you simply say as an object that I want to give you access of this user I also want to give you access of the set user so that you can read the data as well as write the data in this state all right so that's the next step or the step to of having all of this but now I know that my entire app.jsx is actually loading all of this so somehow all of the things which are inside the app. JX should be aware of this how that's going to happen very very simple instead of wrapping it into this uh fragments I can just go ahead and say hey user context provider and it actually Imports it from the perfect place I'm happy with this a user context provider and we wrap this up just like that here and there we go the moment you added this that is it now all of these components which are wrapped inside it are aware of that data now you could have technically uh you could have gone into app this main.js and could have added here that's okay now your app is aware of it inside any component of the app he's also aware of it he or she whatever you want to term it as so this is really nice now we have actually set up the boilerplate code and this is exactly the same syntax that you'll be using your data might be tremendous amount in the smaller amount doesn't really matter but now you have set up the stage so this is a boiler plate every single time you have to do now what's important is how do we actually send data into this state and retrieve that State uh data from back from it so obviously we have already set up the stage for it login will be responsible for setting the data into this one so how do we use it that's where hooks comes up and hooks obviously comes from uh this one just like we have user State we have a hook known as use context so far all the hooks that we have used uh they don't have this much of boiler plate work but this one has and it has its own Advantage you can say now we have this use context so what can I do with the use context is you can actually extract values from it remember the values yeah these values these are props you can extract this data so in the login I don't need whole of data I just need a Selective data because I'll be just adding value to this state so I'll be saying give me that set user uh set user that you have thrown it and how you have thrown it just by saying use context and inside this use context you cannot just go ahead and use it you have to provide a context that what context I'm talking about I'm talking about the user context or the product context I have to for this I have to bring in this so I'll be just saying user context bring it that in and provide that because you can have multiple context context for authentication for user for products different context for different things once I have this one then all I have to do here in the handle submit once the submit button is Click I'll just update the user with that data so first of all just take this event and prevent default once you have done this just use the set user and inside this the set user will be uh adding an object no which will have the access to username and password whatever you are entering it has that now inside this Central store I literally have the access to this so this one is now finally having this value and we have the username and the password access here once I have access of this variable and all these things in here any of my component can go and ask for this data how can it ask yeah it's really exactly same process if you have noticed here the way how we extract the set user which is a method responsible for setting the data I can extract the other thing as well so let's go ahead and do this I'm pretty sure now you can do this as well so const we'll be saying hey let's grab the user because don't want to access set user I want to access the user and use context provide the use cont context again this is not how you should write it because it didn't imported that so I would love to grab it there we go and now write it use context user context basically now since I have access to this I have to do nothing I have to just say hey this is going to be a user but there might be a case that uh there is no value into this one so I can just do some kind of a optional rendering as well conditional rendering as well so I can say if there is nothing inside the user basically it's null then go ahead and return a simple H1 uh that says not logged in and why are you having this issue not logged in oh my bad yeah there we go so if we have the user there we go so very basic very basic code so if we go back here and hit a Reload and it might be uh that I have missed some of the stuff okay uh use context is not okay uh here we are using use context we don't have it really basic we can go ahead and say use context there we go should be all happy there we go uh just for the sake let's reload it says not logged in as soon as I do uh hes here the password field is just a dummy field doesn't really bother us much so if I submit this okay we have some of the issues let's say where we are having this issue uh it says objects are not valid react child find object with the keys username and password ah yeah my bad uh this needs to be fixed let me go ahead and fix this so the error says not a valid react child username so I'm pretty sure I know where the error is uh this is actually in the profile this user is an object because that's what we actually added if you remember in the this one we actually added an entire object and we cannot display the entire object just like this hey dump all the object we need to extract the properties out of it so user do username in this case uh that should fix the error let's go back and I think it should uh let's see no worries I just go ahead and say again H this not logged in submit okay it works uh but the more component should be much smaller and the profile hes should be bigger okay uh no big deal uh we can actually just cut this out and just replace it here that is better yeah there we go so we have this one and by the way if I go ahead and remove everything up here and and there we go and submited it says profile because hey we are still submitting the data it's like empty strings are getting submitted it's not null yet but if I refresh there it's not logged in so again we have to do uh much more check but the idea is not about checking we'll do that in the later on videos the idea is that how any of the component was right now the components were in the same page doesn't really matter but every single component can now access without actually doing a prop drilling which is considered as a pretty bad practice in react my login component is not aware of the profile I don't really care about it it just can set the data into this Global store or the global context from wherever it likes it just needs those methods to set the data the profile on the other hand it doesn't really care who's passing the data we are literally passing nothing it can extract the data from that Global store directly and all I have to do is set up those boilerplate codes and after that all I have to do is make sure all of my components are aware of it either you can do it in app.js if it makes sense otherwise you can take literally this exact same code take it into the main.js and wrap your app with it that's exactly all the components uh should be aware of it that is the whole idea so I told you it's really not that of a bad situation or a bad issue itself uh it's just like it takes a little bit time to adjust with these like I have to create a context then the context needs a context provider and all of that so basically the step is simple create context create provider make sure all all of the people are aware of that there is a context so that I can take the data and send the data that is it that is your introduction to the context I'm pretty sure I have dumbed it down enough so that anybody and everybody can understand it if you enjoy these videos definitely do leave a subscribe to my Channel or hit that uh like button uh that really means a lot if you drop a comment taking out of your valuable time it really really motivates me to make more such video it really takes a lot of effort all right so that's it for this video let's go ahead and catch up in the next one on
Info
Channel: Hitesh Choudhary
Views: 38,860
Rating: undefined out of 5
Keywords: Programming, javascript, reactjs, front end development, learn reactjs, complete reactjs course
Id: aAcI_FdfkA8
Channel Id: undefined
Length: 29min 0sec (1740 seconds)
Published: Thu Oct 12 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.