React Context API with Project | useContext Hook | createContext | State Management Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey everyone welcome back to roadside coder and in today's video we are going to understand context api in react.js so context api helps us manage the state of our react application what do i mean by that let's understand this with an example so here we have got a structure of a simple shopping cart app that we are going to create in today's video so this app has two pages one for products page and other for cards page and under products page we have different different components that are rendered in this screen and we are creating a separate component for all of these products called singleproduct.js now the singleproduct.js will have a button for adding to cart and when we press add to cart button that particular product gets added to our cards page and it gets rendered over here so we are going to need a state for it so let's create a state so we are using use state to create a state for our cart and for updating our cart now we are going to pass this state down to our single product components okay so we have passed it and whenever we press the add to cart button it updates our state of cart now how do we get this card state from our products page to our cards page we cannot just pass it directly like this so there's one solution what we can do is we can take this state and create it inside of our app.js component now this is the part where it gets a little bit uglier we have to pass this state down to our products page which is not using this state at all and then we have to pass this state from product space to single products and all of the single product and then we are going to pass it to our cards page which is only going to use this card component and not this set card but since the set card will be used by singleproduct.js we have to pass that set card from over here then over here to over here so you see this is a lot of prop drilling going on over here we don't want that we don't want our app to look like this because since this is a smaller app but in the bigger apps it gets a lot lot uglier so what is the solution yes you're right context api so let's see how this app will look like with context api so now what we have done is we have created this context over here and we are going to create our state inside of this context now what's going to happen is this state is accessible in whole of our application so let's say if we want the cart inside of our single products.js it can directly take it and call it inside of this component now we don't need to drill down the prop from app.js to product.js and then to singleproduct.js and similarly if our cart page only want this cart variable and not the setcart variable so it can directly take that from our context and similarly for singleproduct.js inside of the card.js it can take both of these state without doing the prop drilling so you see how easy it gets to manage the state of our application by using the context api so without any further ado let's get started [Music] so i've opened vs code over here and now quickly go to file and click on open folder and open the folder wherever you want to create your react app so for in my case i'm going to select this folder and now you need to go to the terminal and type npx create react app and then the name of your app which in my case is context api tutorial and press enter so what is this going to do it's going to go to npm's repository and take all of the things that are needed to create a new react app and it's going to bring all of those things into this folder context api tutorial so let's wait for it to finish and here we go our react app has initialized successfully now we need to switch to that folder we can either type cd and then the name of that folder or we can go to file open folder and then open that folder so here it is let me start our app real quick by typing npm start and here it is our react app has started successfully let's go to our files and let's delete all of those files that we are not going to use so this this this and yeah that's all and now you're going to see that our app will start complaining because it was using those files somewhere so let me just go ahead on app.js and remove everything that's inside of over here remove logo.svg and let's just type hello world yup also let me remove all of the default styles inside of the app.css file now let's start creating few components for our app for example first i'm going to create a header component so header so this component does not exist yet but let me just create it real quick so i'm going to create a new folder for components create a new file for header dot js and i'm going to press r a f c e and press enter and you can see it has emitted this boilerplate code so if you don't know what it is this is an extension that i'm using this is the extension es7 react redux blah blah blah blah you can go ahead and download this so let me just name this header and also i need to import it inside of our app so i've pressed ctrl and space and it's going to show me suggestions and click on it so it's going to import the header also for a shopping cart app we are going to need two pages first one is going to be the home page and other one is going to be the cart page so let me install react router dom real quick so if you don't know what react router dom is it allows us to create different routes for different pages in react app npm install react auto dom and let's wait for it to finish installing six months later 2 000 years later there we go after a quite while react router dom has this finish installing let's close this up let me restart my app so that it doesn't break now let's create the different routes for our app so i'm going to remove this and write browser router so this browser router comes from react router dom so just like this i've imported it and we have to wrap our app inside of browser router if you want to use react router dom so now i'm going to create a wrapper around all of our routes and let's give it a class name of app and inside of it let me create both of our routes so first route will be for our home page let me import route real quick just like that so the path will be slash the component will be home which we haven't yet created but we are going to create it very soon let me duplicate it another component will be for the cart and path will be cart all right great let me just create both of these components so inside of the components folder yes let me write home over here and cart there we go now let me import both of these real quick just like that oops there we go so let's go to our home we are already on the homepage so let's go to cart page and you can see all of the home page and cartridge both are appearing over here it's because we have to add exact over here so that it goes one path at a time now let's start making our header a little bit prettier so inside of this header div i'm going to add a heading below this i'm going to add an unordered list with the class name of nav and inside of it i'm going to create few list items so first one will have a link tag which will be coming from react router dom so let me import a link tag real quick import from react router dom and this link tag will go to slash page and i'm going to have another link tag for our cart page cart yeah just like that let's see yep there we go let me style this a little bit so i'm going to create a new file styles.css and i'm going to write all of the styles for all of these components inside of this file so let me import this file first of all and i'm going to copy all of this styles because i don't want to waste time writing css because this is not a css tutorial this is a context api tutorial so let me save this up okay so i haven't given yep i haven't given the class name to the span so class name header also let me just give these links some global styles so instead of app.css i'm going to write a tag and text decoration to be none and color to be inherit yep that looks much better yup that's right so we can go to our home page or we can go to our cart page great so let me explain these css real quick there's nothing just nothing fancy going on over here uh we're just installing our header to make it look a little bit bigger increase the font size display block and some margin of top and bottom and for our nav as well we are doing display flex so that they appear in the single line and some justify content space around we are creating some space between them and some height and some margin top and over here we are adding the color white to both of the list items inside of our header so and on when we hover on them we're gonna change the color to turquoise okay so i don't know why i gave these two classes let me move this up i don't think we're going to need them now before creating our shopping cart we are going to need some data which will have the list of products so for that i'm going to install a dependency called faker so faker helps us to create a lot of dummy data so let me just go to the browser and search faker let's go to its npm page and there we go we can find the documentation to the faker over here if you want to generate addresses fake addresses we have all of these lists for that and what we are going to use is this commerce section over here we are going to take the price and let's say product name and also we're going to generate some dummy images so for images we have got this random section over here this random section will help us to generate random images so let's go on back to our app and let's see how we can use this faker so it has installed successfully let me close this terminal up and now inside of the home page we are going to import faker from faker and we're going to write const products array and inside of it we are going to generate all of our data so this is just like generating a json file so that you don't have to manually go ahead and do that so let me show you real quick so let's say we want to generate an array of 20 objects so i'm going to write array and inside of it right 20. so what it's going to do is it's going to generate an array with 20 undefined objects and now we're going to map on it so dot map inside of it we are going to write id we will need the id so faker dot data type dot uuid we are going to generate a random id over here and what else we are going to use name ready all right great now let's log this products error real quick let's see what do we get let's go to inspect into the console and we have some error over here let me refresh it okay so issue is over here i have to write price instead of product price so let's save this yep now it's working let's go to the inspect and the console and we can see we've got an array over here with a ton of data so with the random id some image some name and a random price right great so we have our json data generated so let's go on and create the ui for it i'm going to give this dev a class name of product container and inside of it we are going to create a single product component so let me first try to map it so products array oh you know what i'm going to uh store it inside of a state use state so let me create a used state called products and we are not going to use set products let me remove that and inside of it we are going to add the products array let's import use state real quick just like this and let's use our products state products dot map now inside of it we're going to create a component for single product but let's just try to render it inside of the span so prod dot name let's see yep all of these are rendered over here so let me go ahead and create a new component called single product dot js rafce so here we go let me import this over here single product and we are going to send it a prop of product so prod there we go and let's go inside of it and let's receive it over here we are going to restructure it out of it so prod and let me write the code over here just like that so what's going on over here is i'm providing this a class name of product and we are generating an image we're providing we are providing the src of prod dot image just like we had in our data we are giving it some alt attribute of prod dot name and then we are creating a div inside of it called prod dot desk mean product description and inside of it we are giving a prod dot name and product dot price so we so when the price is rendered let me show you let me remove this real quick so you can see it looks currently a lot ugly so when the price is rendered it is rendered just like this with dot zero zero in front of it so to remove dot dot zero zero we are going to just trim it from zeroth index to the third index so it's gonna look like this and at the end we are rendering a button add to cart great now let's add some styles for it real quick so inside of the home i'm going to import our style sheet dot slash styles dot css and inside of the styles.css we are going to add some css for our single product component so first of all this product container is obviously this one which contains all of the products so this is going to be display flex and padding inside of them is going to be 20 pixels i mean padding on the whole of the container and we are going to wrap it and justify content will be spaced evenly let me show you real quick so as you can see let me make this bigger yep also for a single product we are providing it a width of 25 so that it takes a section of our product container over here so we are providing some space evenly in between of those and some margin and some these are just generic styles and some flex direction of column inside of the product so that they are all aligned from top to bottom so image and then the name and add to cart button and some styles for our product description div as well which is this one so don't worry about the styles too much at this point because our aim is to understand how context api works and i'm just trying to create a decent ui for explaining it now next thing that we are going to need is a cart component so let's go to our app.js real quick and let's go to our cart component so let's go to the cart page and inside of this div let's create a span tag with style font size of 30. inside of this let me give some heading my cart below this let me give some separating br tag and as again a span tag with total which will display the total of our cart let's let me write some random stuff over here for now rupees 100 let's give it some style of all right and below this we are going to map to all of the products that ins that are inside of our cart right now so i'm going to give it a div and i'm going to give it the same class name of product container that we gave to our home page and inside of it we are going to map to all of the items that currently are inside of our cart so i'm going to leave this for now empty and now let's see the logic of how are we going to do this so inside of our home.js that is our home page we need to click to this add to cart button and we want this particular item to be added to our cart wait but first i noticed something you can see whenever we refresh our page you can see it's generating some different data so we don't want that we want it to just generate one type of data so i'm just gonna go over here and write faker dot seed and give it some random seed let me give it hundred you can just give it hundred fifty for any any cd as you like so let me refresh it so now you can see it's going to just generate one type of name images might be different but the name and price will be same now what we need to figure out when we click on add to cart we want this particular product to be added to our cart so for that what we can do is we can create a card state over here so use state cart and let me give this an empty array let me let me send both of these props to our single product component all right and let me receive both of these over here so cart and set cut so what's going to happen over here is on click of add to cart is it's going to fire off a function and instead of this function it's going to set our cart with that particular product so we're going to write set cut and we're going to take everything that is inside of our cart from before and we're going to add the prod inside of it so this is how you can add to the cart but we also want to remove from the card so let me add another button over here for remove from cart so in this there's nothing fancy we're just going to filter it out so instead of writing this i'm going to write cut dot filter whichever the product is so right c c dot id not equals prod dot id so it shouldn't match the product dot id and then it should return all of those that means accept that product it should return all of those so if we go on and add to cart so let me just log our cart over here cart object and open our console so okay so it's generating for all of those so let me remove this console log from over here and let's just write it over here in the home page okay cool now if you click on add to cart you can see two items has been added if i write another three items has been added remove from cart okay it has cleared full of our cart so let me see what the issue is oh okay because we are making this operation for all of the products so what we want is so i'm gonna add a check over here if cart dot includes inside of the curly braces since we are writing javascript so if it include includes the product question mark then what it's going to display it's going to display remove from cart otherwise it's going to display add to cart so cut this and paste it over here and otherwise it's going to display this thing just like that let's save it and let's check it out if we click on add to cart it has added this to cart so you can see over here let me remove from the cart yep it has removed that particular product from the card if you remove this we have only one product great now there's one issue over here this card state is inside of our home.js file so how do we get this state to our card.js file so you can see inside of our app.js we have our home state over here and card set so we need to take a state from home and pass it to the card but that's that is not possible we cannot pass the state from child to parent component so there's one solution over here either we can create a state over here inside of our parent component that is app component so let's take this state and i'm going to create it inside of our app.js component great and let's pass it to our home page so let me write it a different way now so we can create a closing tag for route and remove this component and inside of it we can write home and similarly we need to create it for cart as well so let me remove this from here and inside of it let's take this component and add it and let's name this cart all right now inside of our whole home component we need to receive both cart comma set cart all right this should work properly it shouldn't have any error let's add to cart yep it's working fine yeah great also we can see an error over here it should have a unique key prop yes we can add a key over here prod dot id all right great now let's receive this card state inside of our cart let's go to cart component and resave it so cart comma set cart and we are going to render everything that is inside of our cart so cart dot map and we are going to call single product component and provide it the product and let's see if it works fine or not let me just give it key as well let's see if we also okay so these components have already been added to card let's go to the cart okay it's broken cannot read property includes of undefined oh it's because we are not sending the cart and set card from over here so cart and set cart all right great now this should work let's check it out inside of our home page let's add some things to the cart and let's check our card there we go we are getting it from our card we can remove this from our cart as well yep just like that let's let's just write the logic for this total as well so inside of our cart we are going to create a use effect so it's going to run whenever our component is rendered let me auto import user effect just like that and we are going to create a use state for containing the total of our components so by default it's not going to be anything let's import use state now inside of the use effect we are going to calculate the total of our card so how are we going to do that we are going to use something called reduce function so set total and cut dot reduce and reduce takes two things accumulator and the current value so i'm going to add the accumulator plus current dot price current products price all right and we also need to give accumulator uh initial value so i'm going to give it 0 let's say 0 but this won't work because this is a string so we have to convert it into integer or a number so i'm going to write it just like this a number all right and now we're going to take our total and let's replace it over here total yeah let's check it out all right so if we add some products to our cart and let's go to our cart yep there we go it is displaying the total price for all of our products great if we remove it okay it's not uh rendering it entry it's not changing it in real time it's because we have to add a cart dependency in this dependency array now if we go on and add something and if you go to the cart and remove it you can see it's changing in real time also we can display the number of items which are inside of our cart so inside of our header.js we can write over here we can write cut dot length but first of all we need to get this card state so you can see this is a lot of work when we make our app without context api we have to drill the props in so many places so you can see we have created a state over here and we need to pass it to the header component for displaying that counter and we have to pass it to home component and then the home component is going to take it and it's going to pass it to the single product component even though it was not even using it and just like this we are passing it to cart component and then the card component is taking it and passing to the single product component so you can see this is a not a good way to develop a react application so instead what are we going to use we are going to use as context api so for now i'm going to comment it out and let's go to our src folder and i'm going to create a new file called context dot js and inside of this context.js we are going to create a new function so our afce we are going to create a new component just like that so i'm going to name it context and above this we are going to use a function called create context to create our context so we are going to import create context from react and it's going to be a function and let's give it const cart so this is going to be our cart context and we are going to wrap our whole context component in something called a provider a card provider so cart dot provider and we are going to wrap our index.js with the help of it so let me show you real quick first of all it's going to have a children which means whatever it's going to wrap around it's going to take all of those children and it's going to render it inside of it so let me show you how i i'm going to do that so let's take this context inside of the index.js add this context and import it all as well yep just like that so we have wrapped our app with the help of context and now over here we can create our cart component so use state and we can create our cart component over here let's give it empty array and import it from react yup just like that now how do we send this cart component to the other components so we are going to take both of these and we are going to add them to a prop of card dot provider which is value and we are going to add them over here now what this will do is it will make cart and set cart accessible inside of whole of our application so let's go to our home.js or app.js and i'm going to remove this cart and set cart from over here and i'm going to remove it from over here as well from here as well and i'm going to save it and now you can see our app is going to break let me refresh it yeah it's going to break so let's fix it real quick let's go to our home.js and now how do we get those both of those card and set card from our context so what are we going to do let me remove this first so over here i'm going to use a hook called use context so use context so we're going to take out a few things from it and what is it going to take it's going to take the context that we have created so what was our context this this cart is our context so let me export it export const cart and inside of our home.js we are going to receive it so cart so we have two cart over here first one was this cart component another one was contact so make sure you import the one which is context or you can name it something else if you want so just like that we have imported it and let's take out cart and set cart from inside of it and we are going to remove this there we go also we need to import use context so use context is going to be imported from react just like this and now you see our app is working so let me show you what was inside of this use context so if i log it use context and inside of it we were providing this cart let's save it and you can see we have the cart and set cart inside of it as we expected all right great so we have used it over here but we don't need to use it over here since we are not using it inside of the home page so we don't need to bring it inside of the home page anymore and we can remove this props that we are sending to single product now we need to just go straight to the single product and just add the use context over here let's remove these props we don't need them let's import use context so cart is not defined obviously we haven't imported the cart so from the context let's import the cart there we go our app is working absolutely fine now where else are we using this cart and set cut inside of our card.js right so inside of the card.js we don't need to import cart and set card anymore let's remove that and over here i'm going to import it and import use context from react and this cart context as well and now it's complaining you can see that the card component is already defined so you cannot use just you cannot just go on and bring another component called cart so let me just name this cart page let's take it and name it cart page and let's go to our app.js and let's name it cart page or you can obviously could have changed the name of our context as well so now i think it's fine again we don't need to send cart and set card to single product anymore from over here and we can remove this set card since we are not using set card inside of the cart page all right great let's see if our app is working fine or not let's add all of these there we go it's working absolutely fine so you can see we have saved a ton of code over here also one thing i need to do one more thing inside of our header.js we can take use context directly now without just drilling down the props from component to component so just add it over here just like that take the use context and take this cart component and just add the car dot length and if we go on and add the products in our cart you can see it's increasing the number over here yeah just like that so you see how easy it was while using context api to pass down our state from component to component yes you have to do a little bit of setup for the first time but once your app is set up once the context api is set up you're all done you're good to go and you just see we are taking this context and we are without drilling that down the props from app.js to home js to single product and this is a small project in the bigger project the state management gets a lot tougher so it's better to use a state management tool like context api or redux so this was our simple shopping cart app now in our next video what am i going to do i'm going to explain you context api with something called use reducer hook and trust me the use reducer hook adds a super power to our context it's just like using the redux without even using it so let me show you real quick what are we going to create so this is the app that we are going to create in our next video so this has a full-fledged shopping cart functionality that you can add to your own e-commerce project if you want so let's go and add to the cart and you can see the card number is going up and we have a drop down over here we can go to the cart we can see everything we can change the cart number we can delete the components from the cart and we can also delete the components from over here as well also the best part about this app is this filtering the products so we can arrange them in either ascending or descending we can include the out of stock products or we cannot include it we can add the fast delivery only as well so it's going to display the products that are meant for fast delivery only also we can set the particular rating if you want the five star products it's only going to show the five star products or the three star or the four starts and stuff like that and we can clear the filters as well plus we can search a product so we can go and search you can see awesome metal chips let me search i said this one refined yep there we go so this is an awesome app that we are going to build in our next video by using react with context api and use reducer so stay tuned for that video and if you like this video don't forget to click on the subscribe button just go to youtube.com right now slash roadside coder and just click on the subscribe button and press the like button if you like this video so thank you all for watching and i'll see you in the next video bye bye
Info
Channel: RoadsideCoder
Views: 3,960
Rating: undefined out of 5
Keywords: context api tutorial, context api tutorial react, context api react, context api in one video, context api project, react context api project, context api shopping cart, react context api shopping cart, shopping cart react hooks, useContext hook, useContext Hook Tutorial, createcontext react hooks, Createcontext react, context api react js, react state management, react state management context api, state management react, react context, react context tutorial
Id: gQ_l-1zpVBo
Channel Id: undefined
Length: 35min 35sec (2135 seconds)
Published: Tue Jul 06 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.