React JS Interview Questions ( useThrottle Hook ) - Frontend Machine Coding Interview Experience

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
so I've opened Google search over here and let me show you something so if I let's say type roadside coder and search you see we got all the search results over here right but when we scroll down there was a loading indicator and it loaded more posts let me show you if I click on inspect and just open the network tab so if I gradually go down over here as soon as we reach the very bottom of the page you're going to see it loaded more results it made this API call it got the response and it loaded more search results so basically this loading of search result is an API call which is triggered when we are checking the scroll event and when the scroll event reaches the very bottom of the page but when we reach the bottom of the page there are multiple scroll events triggered over here right then why is it just making one API call so let me show you in depth what's going on over there so let's take an example of a Blog website over here so I'm just going to say roadside coder blog and now inside of a Blog website we got multiple posts right so let's create uh some posts over here okay this post I'm going to put it some grayish color we have another post over here and another post over here now what we're doing over here in this blog site is we are scrolling down right we're scrolling down okay we're going to go down even further okay that's fine up until now but notice as soon as we have 500 pixels of space from the very bottom so this right here let's just write it 500 pixels so as soon as we are 500 pixels from reaching the very bottom what this will do it will go on and load even more posts over here so just like this so let's say these are going to be the posts that will be loaded after we reach the very bottom of the website but see we have to put this check right that keep detecting when we have reached this 500 pixels from the very bottom so we will put this check on the scroll event and if you have used scroll event in the past you know that on every single scroll let's say if you scroll one time like this there will be at least 30 40 scroll events that will be triggered at once so to avoid making an API call on every single scroll event we will use a technique called throttling so let me show you what it is so for example let's consider a bunch of different scroll events over here we have this this so let's say all of these lines represent one single scroll event and to avoid making an API call on every single of these events what we can do we can provide it certain time limit let's say for every 500 milliseconds don't make an API call and after that is passed then you can check right over here to see if uh you know we have reached the very end of our page or not so let's say 500 millisecond that we're checking over here and same with after that as well so for every 500 milliseconds we will check if we have reached the very bottom of the page so this will drastically reduce our number of API calls that will be made to the server so this will be the point where we make our first event call and check if we've reached the bottom and after we have passed Beyond this threshold then we will make another API call and and similarly we will repeat this process once again over here until we make our API call or whatever the action that we're supposed to perform right so this is what throttling is all about so let's go on and see how we can implement this performance optimization technique inside of our react tab by creating a custom hook called use throttle which is also a very popular interview question so I've opened vs code over here and let's go on and initialize a new react app so I'm going to say npm create weat at latest and what this will simply do is it will create a new react app inside of this use throttle folder that I've already created now it's going to ask the name of our project I'm just going to press dot so that it creates the project in this folder itself and doesn't create a new folder I'm going to select react as a framework and JavaScript and awesome we have successfully initialized our new react app over here let's go on inside of the s RC and delete the things that we don't need like this assets and everything inside of this app. CSS inside of this index. CSS and this app.jsx I'm just going to put uh div over here which will say subscribe to roadside coder which you should if you haven't yet and I'm going to remove this state and all of these Imports over here as well awesome let's go and say npm install over here so that it will install all the dependencies that is inside of this package. Json folder okay it's finished installing let's say npm run Dev to run our app there we go let's click on over here and our app is successfully running awesome so now what I'll do I'll create a very simple app over here which will make some API call on resizing of our window so whenever we resize our window it's going to perform some action maybe it can be an API call or whatever right so that's going to be very similar to The Scroll example that we saw in the beginning of this video but before moving forward are you passionate about coding and want to be fully prepared to Ace the interviews at the best companies presenting the job ready program by PW skills which provides Tech enhanced training along with Market relevant instruction and critical communication and resume building skills to help you land up to 16 LPA jobs choose from decode C++ with DSA decode Java with DSA or decode python with DSA courses and master Technologies like lead code and get along with Hands-On projects like chess console and GUI based tic tac toe and upon completion you can apply for jobs like software developer and data analyst or even business analyst enjoy doubt clearing sessions practice exercises and Virtual Lab access all bundled with a course completion certificate enroll now and Kickstart your career Journey with PW skills for just 3500 rupees which is a steal compared to the market price of over 5,000 and use my coupon code RC deal to get an additional discount discount so enroll now and unlock your potential with PW skills where quality meets affordability so what I'll simply do over here is I'll just take a use State and import it from react and this use State gives us an array with two things one is the variable which will handle our state so let's say window size another is set window size or the setter function that will be used for changing this variable initial value I'll keep it width and height of our window so width will be window. inner width and height will be window do inner height and I'll have a use effect over here which will simply run an event listener so I'm going to say window. add event listener and I will listen to the resizing of our window so for that we have this resize event and whenever this is resized it's going to call a function called handle resize which obviously I haven't created yet so I'll just just create and also we're going to clean this up as well so I'll just say in our cleanup or unmounting of our component I'm going to say window dot remove event listener I'll say resize and handle resize cool let's work on this handle resize function over here so all this will do is it will just say set window size and this thing it will just update our window with the current width and height and now if we copy this window size over here and let's just let's just render it right away so I'll say window size is window do width sorry window size. width x window size. height so let me show you if we have opened our app over here what's wrong okay use effect is not defined so let's import use effect over here okay let's see y you can see we have our dimensions of the window over here and when we resize our window you can see on every single event it's making a call and updating that value right over here but what if what if there was some API call that was going on inside of it right let's just say any expensive operation or or an API call right then we can't afford to you know call it on every single resize isn't it so that's why I'm going to create a custom hook called use throttle which will apply the throttling performance optimization technique to this handle size function right over here so I can say I'll say const throttled handle resize and I'll just wrap it inside of the use throttle hook that we will create we haven't created it yet and I can just provide it handle resize and also the time in how much time Gap or in how much time frame does it call that particular event right over here right and we can just provide this throttle handle size to over here instead of the previous one now okay let's go on and create this use thrott custom hook so I'll just create a new folder over here for our hooks create a new file use throttle. JS so creating a custom Hook is very similar to creating a react component because a custom hook has the power of accessing reacts internal API that is we can use States inside of it we can use effects we can use references you name it we can use bunch of different things over here right so that is why custom Hook is such an important interview question as well so let's just say const use throttle and this will take two things one is a function or let's call it value for Simplicity and a delay right it will take two things and it will perform the action accordingly and I'm going to export default use throttle let's import it right over here and now let's go on and write the logic for this but before that I need to tell you one thing I have created bunch of different such custom Hooks and discussed a lot of such interview questions in my complete react interview course which is going to be dropping very soon in just a few weeks weeks and if you want to be one of those people who gets the Early Access for the course I have added link to a Google form in the description and in the pinned comment so you can go and fill it out because not everyone will get the access to this course so if you're one of those people who wants the Early Access to this course this will be the perfect time to go and fill that Google form so that I know that you're serious about it and I can reach out to you first before everyone else when that course drops anyways let's move forward and let's discuss how we can create this use throttle so first thing first we're going to be needing a state over here right to handle our throttled value so let's just write it out let's say initialize State and inside of this simply I'm going to create a state to hold our throttle value using UST State yep that's cool Next Step would be to track the last uh execution time execution time just like this you can see over here we need to track this time right if this has been finished or not or the next time has been started or not because if this is finished only then we are supposed to trigger our function so for that what will we use we can't just use State over here because if we use State on every single reender of our component it's going to lose that value right so what we can simply do we can use use ref hook over here so use ref to keep track of the last time the function was executed now the third point is we're going to use use effect for writing the actual logic of our throttling so what uh this will basically do is it will initialize a new set timeout for let's say 500 milliseconds over here and it's going to use this use ref or the reference to check are the 500 milliseconds over yet if they have been over let's just call this function again if not we're not going to call that function right so this will contain multiple steps first of all we would need to set up a timer so I'll just say set up a timer using set timeout to handle the logic and then next point would be inside of the timer call back inside of this set timeout what will we do so I'll say inside timer we will first check the time that has been passed since the last execution so first execution happened over here and the next will happen over here so we will check has the 500 milliseconds reached or not are we in 300 milliseconds or not so similar something like that so I'll just say first check the time elapsed since the last execution and after we have checked it we will perform our condition so if the elabs time is greater than or equal to the specified value that is 500 Mills we will update the throttle value and the last execution time so simply let's say if we have a variable which has been executed let's say third second right so we will keep this third second inside of that variable and then let's say the next execution has happened in the fifth second so we will update that particular variable with 5 Seconds or the fifth second so that we can know that we have to check from 5c onwards now next step would be to Simply calculate the remaining time for next execution if there's any so I'll just say if any and after all of this thing is done I'm going to return a cleanup function as well so this set timeout is running right when the component is unmounted we have to clean up our set time out right so I'll say return clean up function to clear the timer that's it and just in the end we will uh return the throttled value from the hook as simple as that so okay let's keep all of these points in our head and let's go on and write the uh code for this the first step is creating a state so I'll just say use State and I'll just name it throttled value and I'll just give it this function or this value that we're sending to it by default now the next step is to track the last execution time so for that we discussed we can use use ref over here right so we can simply say const last executed and I'll say use ref import it from react and I'll say date dot now we can give it the current time because this is the starting point right now after that we're going to create a use effect right over here and inside of this use effect we discussed that first of all we can create a timer or we can set up a timer so I'll just say set time out this will take uh some value so some delay which is going to be this delay right over here and I'll assign this set time out to const Handler so that we can use this Handler to clean it up later on and set this set time out first step we have to check the time elapsed since the last execution so first of all to check the time elapsed we have to first check what's the current time so I'll say const now equals date do now so this will give us the current time and for checking that time elapsed or the time passed I'll say now minus last execution time or last executed time which is this one and we have to write dot current over here as well because that's what we we do to access the value instead of a reference when we're using the user F now we have to check if the time that has been passed is it more than the delay that we have provided over here which is let's say in our case was 500 Mond right so I'll say if the time elapsed is more than or equals to the delay if that is the case only then we will execute that particular function so I'll say set throttled value to this value right over here and then we will update this last executed to the current time that is now so I'll just say last executed equals sorry last execut current equals now and also this uh set timeout won't run for this delay it will run for delay minus date do now minus last executed do current so that we can keep it updated to the current time and yeah after that what we can do we can simply say return we can do this cleanup over here um this return our cleanup function function so return and I'll just say clear timeout to this Handler yeah clear this timeout right over here and after all of that is simply done we can return our throttled value so okay let's uh go back and see if this is working fine or not I'll just open my browser over here I'll just open inspect let's resize this window something's wrong I guess let's see okay throttled handle resize using our use throttle over here oh one more thing I guess inside this use throttle this use effect will just not be executed once right because we have kept this uh dependency array as empty so we need to keep something inside of it we're going to keep delay and our value if our function changes or our delay value changes because these are the only two things that this whole use throttle is dependent on right so I think now it should work let's find out if I let's close this if I I just resize it you're going to see every 500 milliseconds this is updating it's not updating every single uh you know on every single resize event let's just uh increase the value a little bit so I'll just say 1 second so 1,000 milliseconds over here and now you're going to see see now it's updating on every single uh you know second and even if we stop before this let's say if I did this and stopped it if I did this and stopped it yeah you can see it's still updating after 1 second has been completed awesome so yep that is what use effect custom Hook is all about and as I mentioned if you want to learn more such custom hooks you can sign up for the Early Access of my frontend interview preparation course in that course I've even discussed this infinite scroll example by using throttling so you can find the link to that uh in the description down below and the pinned comment as well so if you like this video give this video a huge fat Thumbs Up And subscribe to the channel for more such awesome interview related videos
Info
Channel: RoadsideCoder
Views: 10,455
Rating: undefined out of 5
Keywords: usethrottle react, custom hooks react, react hooks, hooks in react js, react interview, react interview questions and answers, react interview questions, frontend interview questions, javascript interview questions and answers, javascript interview questions, javascript interview, reactjs interview questions, reactjs interview, namaste react, namaste javascript, react interview question for experienced, react SDE2 interview, react login tutorial, react js login, throttling
Id: VDKMODA168A
Channel Id: undefined
Length: 17min 54sec (1074 seconds)
Published: Sun Feb 25 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.