Learn how to create Custom Hooks in React in 24 minutes (+ useRef Tutorial for beginners)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
what's going on papa fam welcome back to another video today i'm going to be teaching you how to create your very own first custom hook i'm also going to be teaching you how to use the use ref hook but if you're excited smash the thumbs up button row the intro [Music] now before we dive in if you find these videos useful make sure you smash that thumbs up button as it helps the youtube algorithm and subscribe for more content just like this don't forget timestamps are available in the description below so feel free to skip ahead now this video is one of many in my react basics 101 series where i teach you the ins and outs to get started with your journey as a react developer if you're interested in getting this class for absolutely free plus one month of skillshare check this out skillshare is an online learning community where millions of people come together to take the next step in their creative journey the thing i love about skillshare is that there are no ads they're always launching new premium classes and they also recommend really interesting classes so before you know it i'm actually no longer watching tv or netflix all i do is watch skillshare while i'm actually eating my food most classes are under 60 minutes so they should be able to fit any schedule whether you're super busy or you've got a little bit more time on your hands i've actually gone ahead and dropped the react basics 101 entire class on skillshare the first 1000 people to use the link in the description are going to get a free month worth of premium skill share and you're going to be able to with that access the react basics which have uploaded on top of that you're going to get access to thousands and thousands of courses available on skillshare's platform i've actually been checking out a amazing video editing class at the moment by ali abdel where i was actually able to find out how i could use my ipad to add animated handwriting into my videos to level up my production value and now i'm making the best use out of my ipad as well as leveling up my final cut production game so this is just an example of the amazing value that i've got since i've signed up at skillshare and if you guys want to go ahead and benefit from this just like i have then go ahead and remember the first 1000 people to go ahead and grab that link are gonna get one free month of skillshare premium which means that you can access my react basics 101 class it's completely free you have nothing to lose and then after that you can go ahead and continue if you're enjoying what you see on skillshare and welcome back to another lesson today we've got something fun we're actually going to be creating our first very own custom hook so we've seen the power of hooks right we've seen the used hook the use effect hook and there are many more out there and i recommend you look at use hooks.com very very good website to go ahead and look at some hooks recipes that been custom created by other people inside the community but today we're going to build our very own first custom hook and i'm gonna show you how to do it so get excited for that and without further ado let's jump in guys so the aim of today is that we're gonna build a joke generator app right so it's going to look something like this right so we're going to have the joke generator and when we click on generate joke i want this to actually go ahead and generate some form of joke okay so what it's going to do is it's going to pull from an api now this is a public api that i found and what i've actually found is that this api has the following uh endpoint so if we go ahead i'm just going to paste it in at the top here and you can see it's api icndb.com for jokes for slash random and you can see here it actually gives you back a joke right so i'm going to go ahead and make this a little bit bigger it's a simple json response and here we can see inside we have a joke key with a value which is the joke itself okay so this is perfect if we go ahead and refresh you can see it gives us a new joke every time now something cool about this api is that if we go ahead and give it a first name and let's go ahead and say the first name is sunny and the last name is be careful that it's camel case so don't make that mistake if i go ahead and do this it actually goes ahead and uses my name in the joke so it says sunny sanger is the only person to ever win a staring contest against marie charles and stevie wonder so you can see if i go ahead and refresh it's going to keep on coming out with jokes that have my name inside of it so really really cool public api so what we're going to do now is we're going to go ahead back to our code now first i'm going to show you how to use a fetch core to make that request that we saw over here so the simple get request i'm going to show you guys how to do that inside of a use effect and then we're going to refactor that into our own custom hook okay so let's get ready to do that so what we're going to do is we're going to write a use effect over here and if you are unfamiliar with user effects i highly recommend you re-watch the previous video we went over things extensively in that one and it helped out a lot of you so this is a useful call we have to make sure that we import the use effect correctly there we go perfect and what we're going to do here is we're simply going to have a function called const and it's going to say fetch joke right now what this is going to do it's going to be an asynchronous function because it's making an api call and what we're going to have is an arrow function and this arrow function is simply going to go ahead and it's actually going to directly return so we're not going to use curly brackets instead we're going to use parentheses and then we're going to say await because it's making a asynchronous course we want to await the response and we're going to say fetch okay and what i'm going to do here is i'm actually going to go ahead and have backticks for string interpolation and then here i'm going to go ahead and paste the api endpoint okay now remember guys we can actually go ahead and pass the first name uh so in this case let's go ahead and say sunny and a last name and remember camel casing like i said want to make sure we don't make a mistake there right and then the goal is to eventually go ahead and make these variables that we can go ahead and customize now once we've done that i'm going to hit save so it pretty fires and gets rid of a few extra parentheses that we didn't need and then what i'm going to do here is after the fetch is finished i'm going to say then get the response of the fetch because this will come back with a uh a object in the form of a json response like so so what i'm going to do is i'm going to pass this response as a json object okay and then what i'm going to do is that this will then give me the data back right so this will actually give me an object back and what i can do at this point is i can go ahead and i can console.log the data to see what we get inside okay so this will happen on the component mount what we have to make sure we also do we have to make sure we actually call the fetch joke function so let's go ahead and save and then let's go to our right and then you can see it's got a response back so if we refresh just to show you and i drop this down it gives us a response which we've passed so it was a json response but we passed and it gave us a data object and then we can click into value and you can see here is the joke right and you can see there are no such things as tornadoes sunny sanger just hates trailer parks right so there's a few little jokes here i didn't actually get that one but i mean i was laughing at that but um so you can see inside of here you get the actual joke right so it's inside of the data.value.joke okay so what we can do here is we can just double check data.value right save it and then let's go ahead and refresh at this point when you hit the refresh button it will go ahead and have some jokes that are popping up on the screen so some of them are very opinionated um so take it with a pinch of flow but here you can see okay so we do get the data back okay so what we want to do with this information is actually go ahead and store this inside of a variable okay so what we can do here is we can simply go ahead and say const and let's just go ahead and say joke set joke and i'm going to create a piece of state for this so use state and here i will initialize the joke initially with nothing and then once we get that data back what i'm actually going to do is set the joke to the data dot value dot joke okay instead of console logging in and then what i can do is because it will now be inside of this variable i can go down here and i can go ahead and say the following i can just say h2 tag and i can just pop my joke in and then what you want to do as a final step is go ahead and import your use state like so and then you should see compiled successfully perfect and then you can see every time i go ahead and refresh it will come out with a different joke okay so you can see everything works perfectly right so you think it can download emails for his pickup right so you can see everything sort of comes out as we expected it to now obviously the button doesn't work as we want right so what we're going to do is we're going to step this out into different phases firstly we're actually going to create our own custom hook and then we're going to hook it up to that generate joke button okay so what we're going to do now is we're going to create a imagine if we had something like this so the end goal here is to have our own custom hook right which looks something like this it's going to say const joke equals and then we'll say use we'll say use a random joke okay and what i want to do is i want to be able to pass in something like this i want to be able to pass in my first name and my last name and it would just make a joke based on those values okay so what i'm going to do here is i'm going to go ahead and firstly con comment this out so this is just um sort of a draft of what we want to achieve but i'm going to create a new file and i'm going to call this one use random joke okay.js and then here i'm going to use a handy snippets tool so i'm going to say rfce if you haven't got the snippets then make sure you install those and then what we're going to do is you can see it's simply a jsx right so it's a jsx return so we don't actually need the return block over here instead what we actually need to do is we simply need to do a few imports that we're going to need for a sec right we're going to need the use state hook and we're going to need the use effect hook okay so now that we've got everything prepared what we can now do is remember guys that piece of state the joke from earlier right we're actually going to initialize that over here inside of our custom hook because we're going to need to store this value somewhere and then what i'm going to do is i'm actually going to go ahead and cut this use effect paste it inside of my custom hook and then hit save right and then what i'm going to do is over here you can see now that we actually have the use effect we have our joke and it just sets the joke right and then what we're going to do afterwards is we're going to simply return the joke okay now at this point we have hard-coded values we have sunny we have sanger okay but if i go ahead and save this just to demonstrate the first step of getting this to work right so let's just quickly reiterate what we have and also you don't actually need this in the new react version of create react app it is actually not required anymore so you have use random joke we have our piece of state to keep track of the joke we then have a use effect which is triggered only on the hook mount and then what actually happens is it fetches the joke it converts it to json it gets the data from the joke and sets inside of our joke piece of state then it returns the joke so now what we can actually do is we can go ahead and remember this code over here it's going to be nearly that but it's not just there yet but it's going to say const joke equals use random joke and then i can import right use random joke and at this point we can we don't actually pass in any values right it just goes ahead and calls it calls our custom hook and we also don't need to go ahead and have this top line anymore so we can hit save now and you should be able to see compiled successfully and now what you can see is the code actually works the way we previously had it right so this is our first custom hook guys right so we've actually just created our first custom hook so it just says construct equals use random joke and it's honestly as simple as that so you might have thought it might have been a bit more complicated there's a lot that goes to it but this is actually how simple it is so once you understand how to use the use effect you can see how powerful and clean your code can actually become right so jumping back in over here we want to customize this so we can pass in the first name and last name like such right so in like this example over here so how do we do that right so let's go ahead and do the following first let's go ahead and say jim and then as the second one we'll say jim bob so let's imagine we had a person with a first name jim surname bob and we want to pass that into our random joke right so now what we can actually do is very simple actually we can go ahead and just treat it like a normal function so first name last name because essentially all it is is a function right it takes a first name and a last name argument and then what we can do is we can use our string interpolation we can go here we can say first name and last name over here we can go ahead and say last name now before i hit save think about this do we have to update the dependency array with any value right so i'm going to give you just a sec to have a think about this do we have to update the dependency array with any value okay the answer is yes we do need to do that right we need to go ahead and actually add the first name and the last name to the dependency array as now the code inside of the use effect is dependent on two of these variable values okay so this is very important that we get that right otherwise it will result in unexpected behavior so we're gonna hit save okay and then we're gonna go to our app and now you can see it says use random joke for jim and bob so let's go ahead and check if this works so i'm gonna go ahead and refresh and you can say they say curiosity kill the cat this is a false jim bob killed the cat every single one of them right and then go ahead and refresh and you can see it goes ahead and continues to create a new joke with jim bob right and just to prove to you that this works if we say sunny well let's just say papa react save and now it says refresh crime does not pay blah blah blah okay that one didn't do anything papa react grinds his coffee with his teeth and boils the water with his own rage right so you see it works perfectly there right so what we can what we've actually done here is we've created our own custom hook which is working perfectly it takes a first name a last name it uses state it has its own use effect but the key part is it simply returns a value okay so it simply returns a value and here you can see all we do is we store that into a variable and then we move forward from it right so this is really really all it actually takes but what we're going to do now is we're going to take this a step further right we said before that we want to have it so when we generate a joke it does the exact thing and it creates and generates a joke so what i'm going to do now is i'm actually going to go ahead and upgrade this piece of code and i'm going to show you how to use something called a reference as well as two pieces of state and we're gonna upgrade this so that way we have two input fields and the generate joke button right so we're gonna upgrade this code right now just by doing that so the first thing that we need to do is introduce two input fields right now what i'm actually going to do is i'm actually going to introduce a form so if you haven't actually seen the custom form lesson i would recommend going ahead and checking that one out now but here i'm going to go ahead and say input i'm going to have one input and a second input and then i'm going to take this button and i'm going to pop it inside of our form okay so that's the first step the second step is by default is type text we don't need to actually have that i'm going to go to the first form and this needs to have a placeholder and here i'm going to say first name right and for the second placeholder i'm simply going to say last name okay save then what we're going to do is we're going to go ahead and create two pieces of state to keep track of what's inside the input field so here we're going to say first name set first name and then here i'm going to say use a state and this is going to be an empty string copy this and i'm going to go ahead and simply refactor this to be last name and make sure you camel case perfect and then what we're going to do is go ahead and save but it's going to ask us to make sure that we import the use state so i'm going to import use state like such and then i'm also going to go ahead and hook up our input field so here i'm going to say value equals first name and then i'm going to do our necessary on change handler and i'm going to say e set first name set first name to e.target dot value okay and then i'm gonna grab this and i'm gonna do the same thing for the last name as we expect okay so i'm going to go ahead and do this i'm going to say last name and again make sure your camera casing is correct okay so we can go ahead and just check that this works by simply typing in here so we should be able to type in there we go perfect everything works now what we're going to do is we're going to create a function and so here i'm going to say on click and i'm going to say when we click the generate joke button i'm going to trigger a function called generate joke okay so i need to obviously create this function so we're going to say const generate joke and this is going to be a function which takes e as an argument because it's a button submit and what we want to do is because it's inside of a form i'm going to do e dot prevent default to prevent the page from refreshing after i submit that form okay so then final step for this right is that we want to go ahead and only generate a new joke when we have clicked the generate joke button right so what we could do is previously what we could you might be thinking as a solution is we can go ahead and say use random joke and then here you can go ahead and say the first name and the last name the problem with this approach however is that it will make a new request every single time the first name and last name changes right so it's going to be quite chaotic so here if i go ahead and say sunny you see as i do it it creates a new request every single time and even here if i go ahead and do this it creates a new request every single time so it's not actually dependent on the generate joke it's just dependent on the values changing but you can see how it's working in tandem with our new custom hook so that's pretty cool right but what we want to do here is we want to make use of the use ref functionality right so use rep is actually a hook provided by react which allows us to have a reference to an element on the page okay so think of a big finger and it's just pointing at an element okay so initially that big finger is defined with a value of null right but what we want to do is point that at a certain element so that way when we need to get the value of that element the reference that is pointing to the element can give us the appropriate reference okay so here what i'll say is i'll say first name ref so let's go ahead and make a reference for the first name so we'll say first name ref and we'll say equals user f okay so we need to import this from react so make sure you do that and then we're going to give this a starting value of no because remember that p that finger is not pointing at anything initially we're going to copy this and we're going to change rather than first name we're going to change it to a last name and then what we do is we simply connect this to our values over here right so previously you see this is how we would have done things right however it creates a new request every single time so now what we can actually do is make this a little bit simpler we can get rid of all of this and say ref equals and here i can say first name ref right and even here what i can do is i can get rid of this and i can say uh last name ref okay save and then you can see our code's already a lot simpler now what i can do is when we click on generate joke only at that point right so i'm going to go ahead and remove this only at that point do we want to go ahead and grab the value from the input field and update our state which will then re-trigger the joke to be generated again so here what i can do is i can say set first name to b and then i can go into our first name ref so i can say okay get the pointer that was pointing at the first name input field right this has something called current which is a property which says okay the current element that you're pointing at right so we want to get that element and then we just simply have to say value so we'll go ahead and get the element and then it will get the value inside of it okay and then we're also going to do the same thing for the last name so we're going to say last name ref dot current dot value okay and if we go ahead and hit save think about what is happening at this point in time right so the initial value let's go ahead and say is sunny sangha right so the first joke that we see on the screen should be a joke about sunny sangha okay then what we're gonna do is we can fill out the form so this will go ahead and we have a reference to the first name input field and we have a reference to the last name input field but we can see now we're not actually manipulating the state of the first name and last name each time we type and instead now only when we click the generate joke button will it trigger off our generate joke function and e dot prevent default prevents the page refresh and here what will happen is it will update the first name in our state with the first name current value right so the first name reference current value which means it's going to go to the input field which has the reference for the first name right so we use first name reference to go ahead and connect that and it's only at the point when you click generate joke gonna go ahead and grab that value and then it will update the first name and the same happens with the last name now what then happens because of the rules of hooks these values will update which causes a re-render which means that this line of code will get re-executed which means that it will now have the updated first name and the updated last name and a new joke will be generated right so all of this elegance in one line of code so let's go ahead and check this out so sunny sanger perfect is working now if we go ahead and say let's go ahead and say steve jobs and generate joke perfect if you kill if you try to kill minus knife steve jobs programs it backfires right and let's go ahead and do elon musk and i could even hit enter on the keyboard because it's inside of a form in a tag team match elon musk was teamed with hulk hogan against king kong bundy and andre the giant he pinned all three at the same time because we know elon musk is a badass guys so as you can see that was our first custom hook and that was pretty damn fun right we went we then went ahead and upgraded it with the functionality as we showed today and you guys also got your first exposure to the use ref hook right so really really fun stuff here we actually combined not only our custom our first own custom hook but we also introduced the concept of use ref right so the references inside of react and how they can be used to point to certain elements so that way we don't have the unnecessary re-renders inside of our app with that said guys we are now at the end of this lesson so if you found this helpful go ahead and drop a comment below as to what was your favorite part about this lesson and what we're going to be doing in the next lesson is we're going to be building a to do app with react right so this is going to be your first major exercise and we're going to go ahead and use all of the skills that we have learned here to go ahead and build a to-do app inside of react right so this would be perfect for your portfolio it's going to be a perfect little experiment for you to go ahead and test the skills that you've learned so until then guys i will see you in the next video [Music] you
Info
Channel: Sonny Sangha
Views: 14,396
Rating: undefined out of 5
Keywords: react, developer, reactjs, html, css, js, javascript, papa, papareact, papa-react, tutorial, frontend, webdev, dev, clone, backend, fullstack, motivation, reactnative, react-native, redux, typescript
Id: nshyjApIovo
Channel Id: undefined
Length: 24min 9sec (1449 seconds)
Published: Fri Oct 29 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.