Create A Custom Hook in React | React Hooks Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] hey guys how's it going i'm back here with another video and today i decided to bring this video where i'm gonna go over a very core concept and react which is how can you create a custom hook so for those who don't know um within the hook api in react you're also able to create your own hooks and utilize them for many different reasons one of the main reasons is to maintain a more organized code and also utilize reusable logic which happens to work in cases where you want individual states to be isolated and you want to reuse those pieces of logics many times right so that might not be apparent as i explained it to you guys right now however as you work with more um react applications and you implement um custom hooks into those applications you'll clearly see why it is very useful so before we actually get into the tutorial i would like to ask you guys to leave a like because that would massively help the channel grow subscribe if you're not subscribed because um a lot of you guys are not subscribed and it would massively help me reach my 10k subscriber goal which i really really want to and i would really appreciate if you guys can leave a like so let's get into the tutorial so as you can see right here um i already started off with a simple react application already created and the reason why i already created this react application is because it is not important i basically created here a project which is very very simple all it does is it basically has a state called caller and it has a button right on on the page right this button over here and when i click on this button all it does it is basically generates a random color and it changes the background of our page to that random color you can see that i can click it how many times i want and it will continue to generate this and this is actually pretty simple to do all i had to do is um i created a state as i mentioned a state which is called color and it is a string and then in my div over here i set the style first of all i set some width and height which aren't important but i did this so that you can it fills up the whole page but then the background color for the div i set it equal to hashtag plus the value of caller which is our state and the reason for that is because we're actually going to generate a like the color in hexadecimal and we can do that very easily because hexadecimals work through using numbers and letters so in theory we we can just generate random strings and just generate them at the same size as a hexadecimal color should be as you can see we're substituting we're using substrate of negative six and we convert our um string to um base 16 which basically is hexadecimal so that's the idea right um and if this is confusing for you i would recommend searching up on how hexadecimal colors work however it's just as an example as you can see basically this over here is a little piece of logic which generates a random color um in the hex that has more space and in this case over here as you can see when i click the button it just sets the color state to that random color so it's very simple logic however i want to show you guys how to actually convert this into a custom hook so that we don't need to basically have our states existing inside of the same component as our um ui right because we currently have a state over here imagine if we want to have many different states then it might be a little bit unorganized so let's start by converting this into a custom hook so that you guys can understand it better so the first thing you need to do is you need to create a file over here and you need to call it like this um by standards you need to every hook should start with use which is kind of the prefix for a hook and then the name of the hook so i'm going to call this use random color this is the name of the hook that i want and this is the file that i created and inside of here all a hook is is just a function but a function that returns some star some sort of logic right and to do that i'm going to come over here and say const i'm use random color and i'm just going to create this function over here but the important thing is that every hook at the bottom should return something right which is the logic that we want to access whenever we call this hook so for example whenever we we destructure a hook um in react we usually as you can see right here we just structure some values right so whoever created the use state hook knows that this it should return a variable or which is the one we create over here and a function so this is kind of the structure it is defined and these values are returned um through the function so in our case over here we want to return the two pieces of logic that we have in this application right here which is um the state so we want to return the state so that we can access the caller and we want to return a function that changes the state right so to do that we're actually going to delete this over here i'm going to actually import this use state and put it over here and i'm going to delete it from here then i'm going to copy this um state definition and just put it inside of the um instead of our hook and over here all we have to do is we we just need to write our logic and the logic mainly lies in the state creation which is what we did over here and the function which manipulates or mutates that state so that function is this anonymous functions that we created over here so for now what we can do is we can actually i'll just copy this over here and i'll delete this function right over here we're not going to write it over here we're actually going to create a function over here called change color or whatever you want and or generate color something like that and instead of here we want to um set change the state right so we just set the color equal to a random color so these are the two pieces of logic that we had in the in the app.js and now they exist inside of our hook so all we have to do is we have to basically return this to logic now all we have to do is we need to make it so that we can access both the state color and the function change color in the app.js so to do that all we have to do is we just have to return inside of this object the values right so i'm returning color and i'm returning change color so whenever you have different states that you want to access on the hook or you have different functions that you want to access in the hook you can just return them like this and it should work perfectly and at the bottom over here we need to also export so export default use random color over here just so that we can have access to this hook whenever we want to import it so this is basically done and what we can do is we can come over here to the app.js and we can just import here at the top the use random color from and we can just access the file so dot slash use random color and now to access those values we can just say const equal to use random color so we're using the hook and we can destructure both color and change color inside of this so we can access color as you can see and change color and now it should work as you can see we are using color already i just forgot to delete it previously but um color is being generated as the background color and if we want to generate a new color when we click on the button we can just call the change color function inside of here and take a look at this we are only writing one piece of one line of code that actually uses some logic inside of our app.js whilst the app.js can mainly focus on like the ui and the jsx right so over here you can just refresh this it should work when i click on change color it should continue changing colors as if we had all of our states and functions inside of the same component okay so now let's get into an example that is um a little bit harder however it is more applicable to the real world so basically what we're going to be building is a hook a custom hook that will be able to fetch data whenever you refresh the page so that's just like a whenever you want to make an application where you query some data whenever you enter a web page um usually you have a use effect and a state to represent the response from the request and the use effect to basically make the api request immediately when you um refresh the page right however if you're doing this in many different components again it comes to the point where it's you're reusing code for many things and it becomes a little bit messy so what happens is you can create a custom hook which um i would recommend calling for example use query which basically already incorporates all the logic behind the um the fetching the data and also handling the response and you just need to deal with whatever you want to do with the response so we're going to build a simple example of that and we're going to be using axios to make the api request so if you haven't installed axios um i already installed and i already imported into this file over here so to make this work we need to first come up with an example and the example i came up with is using this api over here which is very simple it's a free api if you want to check out this is the url all it does is it returns an image a url for an image of a random food so you can refresh this and you'll see that it will show different in pictures of food and dishes so that's basically the api we're dealing with and what we're going to build is just a webpage which just displayed that image right whenever we refresh the page it should show another image of another dish which is random right so in order to do that we want to create a use query hook so let's come over here and create a use query dot ges and we're going to do it very similar to what we did before we're going to create a function called use query and there is a lot of differences between this and the last hook that we created because of how we usually customize um this kind of hook right so over here we're going to export default use query and let's here at the top let's import whatever things we want in from react so in this case we want to use the use state hook they use effect hook and that's basically it it's going to be from react over here from react so basically what we're going to do is we need to recognize what we want to do here so let's think about this we want this to handle the the basically the logic to make the request and then to hold the state for the response right so in here we need to create some sort of state that is going to hold the response from the api request so let's call this use state over here and it's going to be a print out let's just make it a it should usually be an object so i'll just make it an object and then we'll come over here and say response and set response so what happens is when you make the api request it should return you a response and whenever you make a query and this is where we're going to start this response so that we can access this response in our app.js and we instead of here we need to write the logic for making the request whenever you refresh your page or whenever on the first render right so to do that we use the use effect and now we don't need to use the use effect on every single different component that we want to make this work because we already have a beautiful um hook that we can reuse many times so with the use effect we can just put over here the list of dependencies which are which is going to be empty and inside of here we can put the logic to make the request now recognize this um what are we doing here are we actually going to put the x use request over here well you can do that however i wouldn't recommend doing this because um you there's many different types of things that you can do with your request you can set headers you can pass a body you can do whatever you want and you also want to be able to customize and reuse this to the best of your ability so what i like to do is instead of coming here and saying something like axis.get and just doing the requests out of here i like to actually pass the exes request as a function as a promise into the um parameters of this hook which means that now if i come over here to my app.js and i am going to import the use query hook from the file that we just created use query and whenever i destructure this um use query hook so use query like this and i want to grab the response from this api request so response um i can pass the axios dot get request um like this for example i can pass axis.getrequest and pass the url for the function inside of here so let's just grab the url for the api and just put it over here and now whenever we want to make a different request we can just put it past it as the argument to the hook instead of writing it directly inside of here which makes it a lot more reusable so that we can just put the request over here and now this will obviously return a promise containing the data from this get request so what we can do is instead of this use effect we can just set um we can actually get the request which is request is the promise because it's what we're passing as the argument we can say request that then since it's a promise it should return um a fetch response for example this is how we're going to call it basically it should return promise which returns the response from the api request and let's call it fetch response and in order to set our response we're going to say set response equal to fetch response dot data and the reason why we're doing that data is because if you ever used xs you know that the response from your api request is divided into many different it's an object and the data from that request is contained instead of the dot data so basically we're just setting our response equal to fetchresponse.data which makes it a lot easier because now our response actually works and it's actually making the request so all we have to do is just return this response and now we have a perfect hook that queries data from any api request we want to and all we have to do is um just pass it like this so for example let's test this let's come over here and create an image tag and um pass we know that response should contain an object containing the data from this api request which should be just a single object with um a single element called image containing the url so what we can do is we can say image and for the src we can just say response dot image right because image is the url so let's see if this works um and as you can see it is working whenever we refresh the page it shows an image of a dish um constantly working making the api request and we can just like reuse this how many times we want we can just it is independent the state is independent from each from each other so we can just put this how many times you want i wouldn't know why would you want to do this maybe if you're making many api requests on the same component but to different endpoints this might be a reason why you would want to do this however this is the basic idea so this is basically it i really hope you guys enjoyed this video if you have any doubts i know this topic's a bit confusing but if you have any doubts leave a comment down below um and i'm happy to help i enter every single comment so yeah that's basically it i really hope you guys enjoyed this video and i see you guys next time
Info
Channel: PedroTech
Views: 2,170
Rating: undefined out of 5
Keywords: computer science, crud, javascript, learn reactjs, react tutorial, reactjs, reactjs beginner, reactjs tutorial, typescript, react js crash course, react js, node js, express js, pedrotech, traversy media, traversymedia, clever programmer, programming with mosh, tech with tim, freecodecamp, deved, pedro tech, hooks tutorial, react hooks, useQuery, custom hooks react, how to create a hook in react, learn hooks, hooks for beginners, custom hooks, react hooks tutorial, build a hook
Id: Y9dZ4YLfrhk
Channel Id: undefined
Length: 15min 54sec (954 seconds)
Published: Wed Mar 31 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.