React Custom Hooks | Learn Custom Hooks & Build a Project

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello everyone and welcome to another javascript mastery video would you prefer your components to look like this and this or would you rather prefer something that looks much cleaner more modern and concise like this in this video with the use of custom hooks i'm going to teach you how to make your components efficient and easily understandable all while building a real-life project stay tuned yes this is the project we'll be making a random gif application it's a funny application but it's not about the project it may seem silly but in this case we're gonna learn a lot about custom hooks in depth react reusing logic and making our applications much more efficient why did they choose to explain such a hard topic on such a silly application well these didn't have to be gifs they could be any random data we are fetching from different apis in this case i chose this one because we have two different endpoints one for the random gif as you can see if i click it i get a random gif and one for a gif with a search query so in here i can switch from dogs to cats for example and i can generate new cad gifs that's it as you can see so why this well in this case we're using the same api and both of these requests are really really similar so there will be a lot of code duplication to prevent that we're going to use custom hooks this is a great project to learn how custom hooks work and if you learn how to write custom hooks you're going to be in a minority of react developers not a lot of react developers know how to use custom hooks [Music] the first thing we're going to do is create a new empty folder called gif underscore app just like that then you can open an empty visual studio code window and drag and drop our gif app that's going to open the project right there then you can open the terminal window by pressing ctrl backtick or you can simply head up to the view and then terminal in there you can type mpx create dash react app dot slash this is going to initialize a starter react application right inside of your gif app folder great this is done as you can see our react app is generated we have a lot of boilerplate code in here we won't need most of that so what i usually like to do with create react app is to delete the whole src folder and recreate it from scratch so i just deleted it and then we can create a new folder named src inside of there there is one file that we absolutely need to have that is the index.js this index.js file is the only real connection between our react application and real index.html inside of here we can do import react from react and we can also do import react dom from react dom then we're gonna import app from that slash app we didn't yet create that we're going to do it in a moment but for now let's do react dom dot render and then in there we're going to render that app component our whole application is going to be inside of there and then in here we can choose document dot get element by id and then that has to be a string of root we are targeting that div with an id of root great now that that is ready we can create our app.js file in the src that is going to be a simple functional component so inside of here we can do import react from react const app is going to be equal to a functional component and don't put curly braces here we're going to put normal parentheses because we're going to have an instant return inside of there we can create a div and inside of that dev simply put an h1 that says random gif application okay now what we need to do is export default app with this our application should be ready to start just before starting our application we're going to install one thing mpmi and that's going to be axios we are going to install axios so that we can make api calls more easily once that is done you can run npm start to start your react application on localhost 3000 and there we go if you open localhost 3000 you should see at the top left random gif application now let's go back to our code and import some styles just below the import react from react we're going to type import dot slash app.css we didn't yet create this file but we're going to do that right now so in the src you can create a new file app.css since the point of this video is not for you to learn css i'm going to give you all the css code right in the description as you can see i just pasted it here you'll be able to go down and just find all the css files and simply paste them there that's it now if we save this we should go back to our application and see that something is at least different and there we go just by copy and pasting these styles our application is at least visually so much nicer to work on right now you can close this terminal because we are not going to need it anymore and you can create a new folder in the src folder it's going to be called components in there we're going to have two different components first one is going to be called random underscore v1 dot jsx so this is going to be our first version and the second one is going to be called tag underscore v1 dot jsx so this is going to be finding gifs by a tag now we have the files for two components ready let's create two simple air function components import react from react just below const tag is going to be equal to an error function and in there for now we can simply type return and there we can have a react fragment so that's going to be like an empty div like this and we can say an h1 and then inside of that h1 we're going to simply say tag great now below that we're going to export default tag now you're going to copy this whole thing and paste it over to the random v1 in there the only thing you have to change is tag to random three times if you do that we are now ready to import these components inside of our app.js we can do that like this import random from dot slash components slash random just like that but it has to be random v1 you can copy this line and then simply change random to tag just like this that's good now below this heading we're going to create a div that div is going to have a class name of main dash container and then inside of there we are simply going to render these two components that's going to be random and we are also going to have tag great with that said let's see how that looks in the browser don't forget to save all files as you can see if we go back we have these two new components ready we can start working on them right now first we're going to start with a completely random gif so i'm going to close all the tabs and then i'm going to open random v1 to be able to fetch gifs we have to have the api key for the giphy developers app that's right there i'm going to paste this link in the description that's developers.gifi.com in here you can really easily click get started create your own account and get your api key the only thing you have to do in here is click login login or register with any of the options provided and then you'll be able to click create an app after you click create a new app you'll be prompted with this little window and you can click select api and then click next step in here you can type something like gif app enter a description and then check this little checkbox and click create app once you do that you're going to see your apps and just below you'll be able to see gif app you can copy the api key received and then let me show you what you need to do with it we're going to head back in here and then you're going to create one file in the root of your directory it's going to be called dot env env stands for environmental variables so as soon as we create that in there you'll be able to safely store your api key you can call it like this react underscore app underscore api underscore key then you can put the equal sign and string signs and then in there you can paste your own api key just like so i'm going to paste mine right there and then leave this file great now we saved our api key in the env folder and we have to find a way to retrieve it right here in our component file to get the api key we can do something like this const api underscore key is equal to process dot env dot and then in there you can say react underscore app underscore api key this is going to populate your api key with that we are ready to start making api requests with the default import of react we are also going to import some named imports that's going to be use state hook as well as the use effect hook i would dare to say that these are two most important hooks in react we want to fetch the data as soon as the component mounts for that in functional components we use the use effect use effect accepts two parameters one is a callback function and then the second one is called a dependency array if the dependency array is left empty then the whole use effect acts as a component did mount meaning it only happens initially on the first render so i'm going to say that first render in there we can do something and that something is going to be api data fetching so we have to import axios from axios and now we have to make an axios dot get call inside of there we have to put our url and that url is going to look like this const url is equal to https api.giphy.com version 1 gifs random and then api key like this i'm going to leave this line in the description so that you can more easily follow along and simply copy it with that we have our url and then i'm going to simply paste it here now axios that get called returns a promise so this is a promise and we have to somehow get the value out of that promise for that we can use an asynchronous function so right in here in the use effect i'm going to create an asynchronous function called const fetch gif and that is going to be equal to an async arrow function async and in there we're going to put everything that we have so far const url and also axios that get url why did we do that well right now we can put an await in front of this axios.get and simply store it in a variable so in here we're getting the response and then what we can do is simply destructure the data outside of that response so now let's see what we are getting console log data okay if we save that of course we also have to call our function so just below we're going to call our fetch gif function let's save it and see how it looks in the browser looks like we're getting an error right there and i think i know what could be the problem we can go back in here and open the terminal once again when you add the dot env file you have to restart your server so right there i'm going to press ctrl c to exit it and then run npm start one more time to see if that's going to make a change and there we go as you can see as soon as we refresh one more time there we have our data and that data contains all the information about our gif great and i know that some of you might be wondering why even create this function if you're immediately calling it here why not simply delete that and then declare the use effect as asynchronous but unfortunately that's not going to work as you can see if you save that react says effect callbacks are synchronous to prevent race conditions put the async function inside so we definitely do need to have another function and they even give us an example async function fetch data and then call it down there exactly like we did so that is something you absolutely need to do if you're fetching the data from the api inside of your use effect this is a quite large block of code that's not so easy to remember what i like to do with these kinds of snippets is simply copy them go back in my browser and head to the mem.dev website it's really simple to use the only thing you have to do is log in and then paste that snippet right there i'll head to the create new card button and then in here i'll simply paste my block of code and choose the highlighting that's going to be javascript in our case and what we can do is simply highlight the things we want to learn but first let's generalize it a bit so it's not always going to be fetch gif it's going to be just fetch data so i'm going to just change this to fetch data and fetch data right there then what we can do is remove this url because we don't need to care about that i remove that we only care about how do we actually fetch the data so this is how we do it we have a function and then we can have a function call where we are fetching the data so what is the thing you want to remember well you can highlight anything you want for example let's highlight how to make this function we can also highlight the whole thing and you can even highlight the entire use effect now i'm going to say i just learned how to use async use effect and i'm gonna save it and our snippet of code is saved now tomorrow morning when i continue practicing javascript i'm gonna head to memdev and then it's going to prompt me to train on that same snippet until i fully remember it that's it i do that with all kinds of snippets with that said we can actually continue with coding let's see what's inside of the data well if you had to chrome in the console you can see that data is the huge object with lots of things inside of it the thing that we need is going to be data dot data dot images and then downsized large so we have to get that let's do it right now we're going to store that in a variable const image src and that's going to be equal to data dot data dot images dot downsized underscore large dot url now let's console.log that to see if we correctly stored it as you can see there is the url to our gif let's go back and see what do we want to do with it there's no use in simply console logging it what we want to do is set it to the state so i'm going to create a new state field at the top in there const gif and set gif and that's going to be equal to use state where we're going to pass in an empty object or since it's going to be simply a url we can pass in an empty string and then in here line 17 we are simply going to call set gif and we're going to pass in the image src that's it now we have access to this gif in the state and we can use it down below in our jsx so how is our jsx going to look like well we're going to have a viv inside of the gif we're going to have an h1 tag which is simply going to say random gif just like that and down below we're going to have an image image is going to have the width of 500 so you can set the width to 500 and it's also going to have an src set to gif and it's also going to have an alternative tag which is going to be equal to random gif or gif that's it for now that's enough let's see how that looks like in the browser i'm going to save it and head back there we go as you can see we get a random gif now what we want to do is add a button that's going to recall that same api call so let's do that right now to do that we're going to create a button tag and inside of there gonna say click for new just like that of course this is a button so it needs to have an on click handler or onclick and then in there we're going to call a function called handle click just like that we didn't yet create that function but we're going to create it right now in here i'm going to create that function called handle click and in there there's only one thing that we want to do basically the same thing we are currently doing here so first of all it won't make sense to simply copy and paste all the code what we're going to do is we're going to take this fetch gif function outside so that we can reuse it both here and here i'm going to copy the fetch give function take it outside and now i can paste it in here at the top cons fetch gif we are using it right here but we're also gonna be using it right here below in the handle click we're calling the same thing getting the new gif and setting it to the state on the click as well as initially okay now let's save that if you head back you should see a button right now and when you click it you should get a new gif and that works perfectly i see it's not perfectly styled so the only thing you have to do is add a new class name here and that class name is going to say container now if you go back it should look better there we go it's centered and we have the button just below as you can already see there is too much happening in regards to logic react components should be simple they should only be returning some jsx and as you can see in regards of jsx this component is fairly simple it has four lines but what's cluttering it is the logic so we have to find a way to bring this logic outside of this component but before we do that let's also implement the tag function so the tag functionality for getting different gifs by a tag name not just at random to prove my point that there's going to be a lot of duplication we're not going to start creating this component from scratch we're going to take our whole random v1 component and we're going to copy it all of it and then paste it right here we're going to continue from this thing because it's going to be really really similar the only real difference we have to make is in here add a new state field for the tag we want to search for so you can say tag and then say set tag and then use the state and initially set it equal to an empty string then just below you can say random we can use the tag random tag gif so this is going to be for example random cats gif if you search for a cat and then the only thing we need is going to be an input because we have to select our tag so input is going to be a self-closing tag it's going to have a value of a tag and it also has to have the on change listener the on change is going to have a callback function where we get an event and then it's going to be an instant return where we're going to set the tag to be equal to e dot target dot value what we're doing here with this on change is we are registering all key presses and then we are simply setting them to the tag so if you type a b c then the value of tag is going to be a b c great with that let's see how we can make an api call not only random but also to a certain specific tag to do that our fetch gift function is going to accept a tag and then we have to make use of that tag in the url the only thing you have to do to the api to change it is add an end sign and then say tag is equal to a template string tag there we go you can see we just added this little part i'm going to paste this link in the description also so that you can use it now in here the data is not going to be for the random gif it's going to be for a tagged one that's great now you can see our fetch give function accepts one tag one parameter but we are not passing any so now we can use the stack property and pass that over in both of our function calls that's going to be right here on the handle click but initially we don't have it so initially we don't have any tags selected so what we can do is we can specify an initial one let's do dogs great if we now save that let's see if it's going to work if we go back to the browser and close this you should see that we have random gif and looks like our tag is not populated here so let's see what's happening we are only setting it in here but what we want to do is rather immediately set it in here so in here we're immediately going to set the value of our tag to dogs if you now save that in here only pass the tag let's see what's going to happen if we go back you can see random dogs gif and then in here pre-populated dogs but we can now change that to cats as you can see we get cats and you can also click click for new which is going to generate a new cad gif great this means that the functionality of our application is now fully done what we're going to do now is the main part of this video we're going to take all of this duplicate code a lot of the logic we're going to simplify it from this component and also from this component to make something concise nice looking and efficient using custom hooks first thing that we're going to do is create a new file in the src folder in here we can create our custom hook and it's going to be called use gif dot js all hooks must begin with the word use at least that's what the react theme says to start i'm actually going to copy all the logic from the tag v1 file right in the use gif let's start by copying again the whole thing so the whole file i'm going to immediately copy it and paste it into the use gif inside of here let's get rid of some things that we won't need for example we definitely won't need the jsx that stays in the components what else can we do to simplify it well let's bring our url to the top so i'm going to extract it right here just below the api key and then i'm going to remove this tag part at least for now i'm going to remove that there great and then this is not going to be a con strand of component this is going to be a function more specifically it is going to be a use gif function just like that it's going to accept one parameter and that parameter is going to be tag so if there is a tag we're going to send it over as a parameter that means that we don't have to keep track of it here so i'm going to delete this line and we're just going to keep our state gift as you can see even though this is a custom hook we still are using the use effect and the used state hooks we are allowed to use built-in hooks inside of our custom hook but we are not using react so we can just do it like that you can see our use gift function is not being used so the only thing we have to do is export it just below use gif export default use gif great so what do we have to do to make this custom hook work well first of all you can see we are not returning anything so what do we actually want to return well we're going to return a gif like that right we want to use that gif that we have here in the state our function for fetching gifts is still the same but you can see we have the tag here that is not being used so inside of here we're going to make it dynamic and how do we make it dynamic well we can use the itinerary operator so inside of here we're going to say if there is a tag then the url is going to be equal to to the url and then ensign tag is equal to tag just like that else the url is simply going to be equal to url that's it now we have the dynamic url which is going to work for both when we have the tag and when we don't have the tag and then we set that gif to the state as you can see our use effect stayed the same it's still fetching the gif with the tag in there if we do have it and then finally we won't have the handle click right there so we can simply get rid of that now we can save that and that should be it we created our custom hook it has the gif in the state it has a function for fetching gifs and then finally it fetches gifs immediately at the start of our application but we don't only want to fetch gifs immediately we also want to fetch them on click for that reason we are not only going to send over the gif we are rather going to send over an object that's going to contain gif and it's also going to contain the fetch give function so that we can use it from our components that's it our custom hook is ready now how do we make use of it to make use of it we're going to create two new components random underscore v2 dot jsx and also tag underscore v2 dot jsx inside of there let's again create simple arrow function components so import react from react const tag is equal to a function in there we're going to have a return and we're going to return the same jsx as we're turning in the tag one but for now let's leave it like this and finally export default tag great now we have to take some things from the tag version one we're not going to take a lot of things but we do have to take the use state we also have to get the handle click and we have to get the jsx so let's start with our use state in here i'm going to take that and simply paste it in here then i'm going to import the use state because we're using it and what we have to take is also going to be simply the handle click and the whole jsx so i'm going to copy that right now with that i'm going to paste it here and that's it you can see we are still missing the gifts and the fetch gif but if you remember correctly these two things are the exact things we are exporting from the custom hook we've created so to get to that we have to import that custom hook import use gif from dot slash and then that's going to be use gif now we can use it as a hook we can say const in there we can put a gif but we have to use object destructuring because we exported those from an object and then we have the fetch gif and that's going to be equal to use gif where we're going to pass in our tag that's it and if you save it that should be good we can even simplify it forward to move this into one line or even simply take the value out of it and instantly put it in here because of that we don't even have to have the handle click so now let's copy this whole thing from tag version two and let's move to random version two i'm gonna paste the entire thing right there and the random version two is going to be even simpler we can remove the use state right there we don't need the state because we have no tags and then we simply need gif and the fetch gif and that's it everything else is the same if you remove this tag right there and in this case we don't have the tag so the only thing we'll be doing is simply fetch gifs so you can remove this whole thing and simply say fetch give random doesn't have an input and also doesn't have this tag right there and that's it if you save it you can see how simple this component looks like it just has all the necessary jsx and it's immediately telling you i need the gif and i need the fetch gift function and give me those from the use gif custom hook same thing with the version 2 of tags i need a gif i need a fetch gift i'm controlling some kind of state there and i'm passing that state over to use gif give me some gifts back that is it now if you save that let's see does that actually work there we have it random dogs gif as you can see click for new we're getting some nice looking dogs gifts and we can also change it for cat there we have it and you can click new for random gif as well that is it you just learned how to create custom hooks to make your code more readable and more efficient by the way the complete path of javascript mastery course is soon going to be released with it i'm also planning on releasing a lot of react courses these react courses are going to be focused on building certain projects they're going to be really in depth if this sounds like something that interests you make sure to sign up for the mailing list to be sure not to miss the courses when they come out with that said thank you so much for watching and see you in the next one [Music] you
Info
Channel: JavaScript Mastery
Views: 28,176
Rating: undefined out of 5
Keywords: react, reactjs, custom hooks, react custom hooks, reactjs custom hooks, build custom hooks, create custom hooks, create custom hooks react, react custom hooks tutorial, react custom hooks example, react custom hooks api, build an application with react, real world app using react, react build a project, custom hooks reactjs, reactjs custom state hook, react hooks, react js custom hooks, create custom reactjs hooks, react js hooks, react hooks tutorial, reactjs hooks tutorial
Id: O6FhJvcvVOE
Channel Id: undefined
Length: 30min 59sec (1859 seconds)
Published: Thu Sep 24 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.