React Debounce Search Input API Call | useDebounce React Hook

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
I've got a react search app that requests data from Wikipedia using SWR and axios it works well but every time I type in the search input it sends a request that's not efficient and it abuses the Wikipedia API but we can fix this problem if we debounce the search input [Music] hello and welcome I'm Dave today we will debounce the search input in a react app and I'll provide links to all resources in the description below I'll also provide a link for you to join my Discord server where you can discuss web development with other students and you can ask questions that I can answer and receive help from other viewers too I look forward to seeing you there a quick note today this is not a tutorial for beginners and I'm going to move a little faster that said I will explain everything and if I'm going too fast for you remember you can pause the video to look at the code on the screen and you can download the source code from the GitHub Link in the description and if you want to complete this project with me I do recommend downloading the source code because we're already working with an app that's already created I won't be going over each component I'm just focused on the task at hand which is debouncing the search input so let's once again look at the problem before we look at any of the code over here and I will drag this over to the full screen once again then I need to open the dev tools and look at the networking Tab and so here we've got reactive tools loaded in but I can just clear that out so we just see what happens when I start typing in the input and if I type my name Dave it has four letters and you see this flash over here because we're sending four different requests so there were different results and it changed that as well that's not great but also we had these four different requests in the network Tab and even if I delete my backspace there's another request and so now it just searched for DAV and we got different results that's not what we want we want to wait until we have finished typing we've completed typing whatever we're going to we can't really figure that out exactly but we can put in a amount of time a certain amount of milliseconds or maybe even one second which is what I'll use today to really highlight the difference and then of course I think you'd want more like 500 milliseconds to really use this but what what we'll do is put in that amount of delay and that's debouncing the input and then we'll send the request and only after that amount of time that amount of delay is when the request will be sent so I'll close devtools again drag this back over to the right and really we want vs Code full screen for most of this let's start by looking at the package Json file and remember if you download my code from GitHub you want to run npmi for install to install all of the dependencies really I've only added two dependencies today we've got axios here and SWR and if I open my terminal you can see I'm already running a Veet here on localhost at 5174 I think you might run 5173 by default but you can do either one anyway we've got a second terminal window open now and so if you were going to install the dependencies after downloading the code from GitHub you would just type npmi or npm install either one and it would add all of those dependencies that you need okay after that let's go ahead and take a quick look at the axios API layer before we look at any components so I open the source directory from the starter code go to the API directory and you can see I've named this file Wiki API so inside of this file just a couple of things I want to highlight even if you're familiar with axios and have used it several times one is I'm creating this API here called Wiki API with the base URL and this is the information here and I'm going to put links in the description if you want to dive deeper into the Wikipedia API because there's really a lot to it but there's a lot of parameters here and I just want to highlight that I put all the params this is a get request and if you don't specify the method it defaults to git but I put all the params in here and we're just passing in the search term to our get Wiki search results function and then instead of what you may be used to seeing like API dot get or API dot post or something like that I'm just saying Wiki API dot request because we're just using the base URL there's no further URL to pass in and append to this so just Wiki API dot request letting it default to the get method and these are all of the params we're sending in the URL to Wikipedia now let's take a quick look at our react components and here's the app component you can see we are using state to set a search value and we have the set search value function as well we pass all of that into the search input component and then we also have a list component that only receives the search value so if we look at the components and we look at the search input you can see that is all that is here is the text input and it is a controlled input so the value is the search value and the on change triggers the set search value function and that's essentially all there is to that which pushes that back up to the app.js which can then send then the search value down into the list component as a prop so once we look at the list component we can see how we are fetching that data so we get the search term here in the list component and we're using SWR SWR uses that get Wiki search results function that we already looked at in the wiki API here is something that triggers the request now if we have a search term we're using a ternary statement here then the search executes but if not this value is null and this does not execute so that makes SWR great for this type of thing so we can just put that in here and we're not always executing a request we're not always sending a request I should say we only are if we have a search term however before bouncing the input we always have a search term every time we type into that input so that's essentially what's going on there after that we just use the different states is loading error and then data and really the data you get back from the Wikipedia API is a complex object so we're going several layers here we're looking at data then queries then pages and even once you get to Pages it's a object with a lot of objects inside of it so even then we have to say object dot values and then map over those results and then the item component just presents those results and so the only changes we're going to make to these components will be here in the list component where we apply use SWR and in the app component where we have the search value and so to debounce the search value or the search input what we need to do is create a use the bounce hook so let's highlight the source directory here create a new directory called Hooks and then inside of this directory I'll create a file called use with a lowercase U and then a capital D for it to bounce dot jsx now before I create this hook I want to mention that I have another tutorial on creating a debounce function in vanilla JavaScript and it may help your understanding to also watch that tutorial and I'm going to link to it in the description and you can see how react achieves the same thing differently than how we do it in vanilla JavaScript so that could just add to your comprehension of the whole concept essentially okay so let's go ahead and create this hook I'm going to start by importing use effect and then I also want to import use State both from react and after that I'm just going to go ahead and do the rafce well it's not wanting to cooperate there let me see if I can get it no I don't oh there it is all the way down here in my list I need to maybe fix that in my settings there we go so now basic use to bounce hook here now it's going to receive a couple of things one is whatever value we pass into it and another is a delay and I'm going to set a default value for this delay of 500. so if it's not passed in it's going to be 500 milliseconds by default now let's go ahead and use the state so I'll say const and we're going to create a debounced value and we'll create the set the bounced value function I said the bounce value debounced value function and then after that we need to go ahead and just set use state and let's start out by just passing in the value that is passed in for the initial value that's fine okay we need use effect now so here's the use effect hook and inside this use effect hook well let's go ahead and put the dependency array here as well now inside the dependency array we're going to need both the value and the delay let me separate that from the return here just so we can see it a little bit more clearly or at least I can now here I need to Define an ID I'm going to set this equal to a set timeout and now set timeout has a function inside of it and inside of this function is where we're going to set the bounced value equal to the value that is passed in and here we can put in the millisecond delay so we'll just put in that delay value right there so we've defined this now we need the ID for the timeout that is set so we can also cancel it and use effect has a cleanup function and that's the ideal place to go ahead and clear the time out so we'll say return I'll have this function here and then below we'll just say clear time out just like timeout itself up here this is something that's available in JavaScript already we don't have to Define set timeout or clear timeout here we just pass in the ID so it will clear the timeout that was created now notice I brought this on a separate line and I did the same up here that's because I think we should put in console log statements to help see what's happening at first so I'm going to say console log and then I'll say setting new timeout and then here of course we'll put clearing the timeout so console.log and we'll say clearing the timeout just so we can see what's happening at first and then of course we can come back and delete these log statements and now all we really need to do here at the end is return that to bounced value so to sum up what this hook does is it receives whatever value is passed in and we'll be passing in the original search value and then it sets the bounced value after a certain delay and so whether that's a half second like 500 milliseconds or a full second or whatever we set it to we don't get that to bounce value back until after the delay essentially and of course every time you set a timeout you need to clear the timeout and that's what we're doing with the cleanup function so it's fairly simple overall but we're adding a delay in for that debounced value and now with this hook created we need to go back to the app.js component and apply it we'll start by importing our custom hook at the top so we'll say import use the bounce and it comes from our hooks directory after that we can go ahead and Define our debounced values so we'll say const it bounced search value and we'll set this equal to use the bounce let's pass in the initial search value that we have in state above and then I'm going to put pass in 1 000 milliseconds so it will really kind of highlight the delay it'll feel a little long I think 500 feels a little more natural but after that we're passing the search value in here and so instead of passing the search value down here to the list component we want to pass in this to bounced search value as the search term so again before we try out the new to bounce feature that we have just added let's once again look at the list component and we're still we're bringing in that the bounce value now as Search terms so we really don't need to change anything here I just want to highlight what is happening because the debounced value will have no value it'll essentially be empty at first and so it will fail when we get to this ternary and the value will be null and no request will be issued and that's how easy it is to apply this to SWR so now let's go ahead and look at our app once again I'll drag this over Let's Go full screen with the application and I'll open up the dev tools and here we're in the network tab once again in Dev tools I'll clear this out I'm going to type my name again and let's look at how many requests happen I typed my name we waited one second and then only one request was issued instead of four which were issued instantly after every letter I typed before now the same thing when I backspace as long as I don't stop no other request was issued and no request was issued when this was empty because once again it was not true it failed that ternary statement so I could type something like hey now another request is issued and if I just backspace once and wait a second then a request is issued so as long as I am in action typing nothing else should happen so I could type gym for example and now we have another request and we see all the results for Jim and Jim Henson reminds me of Muppets so as long as I'm typing no other request happens and then it happens one second after I finish so again you might want to lower that in your code to 500 milliseconds it might seem more natural so a quick final touch that I didn't want to add until I displayed how this worked in the network tab because it will add more Network requests but that is we can add some images to these results as well so let's go to the components once again look in the item component and you'll see where I commented out some code you could uncomment that but remember to delete this code underneath that just defines the content right here so starting on line 36 to 40 delete that code and then uncomment the larger block of code here from line 14 to 34 and now we'll start to bring in some thumbnails with these results but that will show more requests because it has to request all of those thumbnails as it brings them in so now you can see our results over here if a thumbnail exists for the result and you have to check for that because they do not all have thumbnails but if it does exist you will see a thumbnail in the results so if we search for Dave once again let's see who all has a picture a lot of Dave's have pictures so that improves the app just a little bit now I hope this has helped you learn more about what the bouncing is and why it's necessary when you work with API requests that are tied to an input now here's a challenge for for you take this project and make it better in the last few weeks I've covered SWR skeleton loaders and react suspense and error boundaries they can all be applied to the simple app and it will make it better for your portfolio you can also add your own CSS to make this project different from everyone else's and that's a good idea so add those features and share your results remember to keep striving for Progress over Perfection and a little progress every day will go a very long way please give this video a like if it's helped you and thank you for watching and subscribing you're helping my channel grow have a great day and let's write more code together very soon
Info
Channel: Dave Gray
Views: 19,888
Rating: undefined out of 5
Keywords: React Debounce Search, react debounce search input, react debounce search api call, create a search bar with react and debounce input, react search, react debounce, react search input, debounce search input, debounce search, debounce, react, react js, usedebounce, usedebounce hook, react usedebounce, usedebounce react hook, debounce react search input, debounce react search, debounce api call, debounce api request, axios, swr, debounce axios, debounce swr, debounce axios request
Id: MHm-2YmWEek
Channel Id: undefined
Length: 16min 9sec (969 seconds)
Published: Fri Feb 10 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.