React JS Interview Questions ( useEffect Hook Polyfill ) - Frontend Coding Interview Experience

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
so interview questions like this generally start very light first the interviewer will ask you what is a use effect hook and what are its uses and then as the interview progress is he will ask you to make an custom implementation of the use effect hook so let's see how we can answer these questions but before we do that hit that subscribe button right now if you want to see more such videos like this because you won't find content like this anywhere else on YouTube so first of all what is a use effect hook so use effect by definition is a hook using functional component in react to perform side effects after rendering such as data fetching subscriptions or manual Dom manipulation let's see what I mean by that let's take an example of a data fetching so here I've initialized a new code sandbox so I'm going to create a simple use effect over here so use effect takes two things one is a call back and second is a dependency array and let's see if I write something inside of it let's say log fetching API and let's save this now notice when I reload this see we're getting this message fetching API over here so when we have kept these dependency array as empty this use effect will run for the very first time and the only time during the life cycle of this component in a scenario like this I can use this use effect for fetching the API so okay I'm going to create uh three states over here for storing our data loading and error just like this let's import used State over here use gives us two things one is the variable and other is the function for changing that variable and it takes the initial State over here which I'm going to give this an empt array for our data and loading it's going to be true and error it's going to be null now inside of a use effect hook I'm going to write the code for fetching our API but before that let me just create a function over here const fetch data and this is going to be an as synchronous function since we're going to fetch our API inside of it so also so I'm just going to take a try catch block to handle our errors so const response await and fetch and I'll just take simple Json placeholder API so let open another tab Json Place holder and instead of this let's just take this posts okay I'm going to take this endpoint and I'm going to paste it over here so it's going to fetch all of the posts for us and it's going to give us some data now over here we obviously need to format that data so first of all I'm going to check if response. okay if response is okay I mean response is not okay we have kept not over here so I'm going to say Throw new error response not okay else I'm going to say const fetched data equals wait and I'm going to format this data so I'm going to say response. Json and now inside of it we have our final data so we can just say set data to fetched data and if there's any error I'm going to just say set error to error and finally so inside of the finally block this finally code runs every single time even if the API fails or if it executes successfully so in finally I'm going to is set loading to false simple now we can simply take this fetch data and call it inside of our use effect hook so what this will do is it will only call this fet data when the component renders for the first time so all right let's see if we go to our Network should have fetched it uh yeah there we go posts and in the response there you go we're getting all of our data cool now over here let's go on and render all of our data so simply what I'm going to do I'm going to take a unordered list inside of it I'm going to do a map for our data map return and obviously I'm going to take post over here to render it and I'll just say return Li let's say post. title so if I reload this app notice it fetches our API in the first render of our app and that is what the major use case of a use effect is whenever our component renders we can perform some side effect so this is one way of invoking use effect now there are multiple different ways of invoking use effect as well like we can put something inside of this dependency array we can get rid of this dependency array as well or we can do some cleanup tasks but before moving forward are you ready to become a full stack developer in your own language meet gooy an IIT Madras bagged HCL Group Company teaching Tech in languages like Tamil telu Hindi and more over 2 million folks have learned Tech with gooy and here's the best part no special qualifications needed just bring your interest and passion in 3 to 5 months students and working professionals can learn the latest tech tools like nodejs mongodb and others in your own language plus get full support to find a job afterwards make apps like Instagram Gmail and Spotify to show off your skills learn from experts at Google Microsoft and more big companies start with a risk-free trial join a pre-boot camp for a week after paying a small fee if you like it jump into the main boot camp if not get your money back no worries get live classes for 3 to 5 months with experts access recorded lessons forever ask questions anytime and practice heaps on gooy school platforms get ready for jobs practice interviews build a resume and create your online profile find over 20 job chances based on how well you do with salaries ranging from 3 LPA to an amazing 21 LPA Kickstart your career with goo's full stack development course don't just dream make it happen check out guy's website now and start your text Journey today link is in the description down below and pinned comments so I'm going to get rid of all of this code over here and I'm going to create a simple counter example so obviously this counter doesn't exist yet so I'm going to create a new folder components inide of this I'm going to a new file called counter oops counter. JS and to save our time I'm going to bring the code that I've written already so let me just show you Yep this is the counter code so what's happening over here we have a state called count we have another state called count one don't pay attention to it just yet let me just import use effect first Al so I mean use State and use effect first yeah so we have a state called count and we have two functions over here increment and decrement which are changing that state whenever we click on these buttons so when we click on increment it's going to increment the account if we click on decrement it's going to decrement the account and it's going to render the account right over here so okay let's uh export this export default counter and inside of our app.js let's import it there we go if you click on increment it's going to increment if you click on decrement it's going to decrement cool now notice I've have put this console log over here called render first of all I'm going to get rid of this console log I'm not going to show you just that just yet so okay so whenever we click on increment this state changes and react Works in a way that whenever a state changes it reenders that component so when we click on increment you're going to see component is rendering every single time this state is changing whenever I'm increasing it or decreasing it all right so we have this use effect over here and we have kept the dependency array as empty so now obviously as you already know it's going to run for the very first time and then it won't run at all so let me just refresh it see effect triggered for the very first time and whenever I click on increment or decrement it's not going to get triggered anymore right so this is the first use case of use effect now there can be an other use case as well for example if I keep this count inside of it now whenever I click on increment it's going to be triggered every single time this count changes and showing the real time value of the counter as well okay but what happens if I change this state over here this is inside of this uh use effect but let me just bring this state and put set count one over here so now whenever I click on increment or decrement it's going to change this variable and not this variable so see let me just clean it notice the use effect is not getting triggered because this value over here is not changing even though our component is rendering as you can see but this value over here is not changing therefore use effect is not getting triggered awesome but what happens if I get rid of this all together so let me just get rid of this and now okay now if I click on increment decrement see every single time use effect is getting triggered on every single reender now doesn't matter what you reender it's going to still get triggered so right now I was changing set count one but what if I'm changing just set count let me just remove this one now if I click on increment or decrement it's still going to get triggered because in this state when the dependency array is not there it's going to get triggered every single time now what is a cleanup method in use effect so cleanup basically is done by using this return so we need to do return and we need to provide a call back over here now this return will only be invoked if the dependency array that is this dependency array over here let me put count over here if this changes or the component gets unmounted so if I just click on over here and say log now let's clean this up and if I click on increment notice since this count changed cleanup was invoked but if I remove it's not going to get invoked anymore and one more case is that when the component gets unmounted so notice it's still going to get triggered over here so these are the use cases of use effect and how use effect works now let's go on and see the custom implementation of use effect hook but before that if you're preparing for your frontend interview and you would like me to help you in your front end interview preparation just click the link in the description down below and book a one-on-one call with me we're going to discuss tips tricks I'm going to give you a lot of resources I'm going to design a proper road map tailored to your situation which is going to help you out a lot in your front end interview preparation so click the link in the description down below and book our one-on-one call with me so I'm going to open our files and I'm just going to create a new folder called hooks because this is a good practice to create a separate folder for hooks as well as for our components as well so I'm going create a new file use effect or use custom effect. JS and creating custom hooks is not a rocket science it's very very easy so it's just a simple function so const and a simple function just just starts with keyword use so I'll just say use custom custom effect and this will take two things as we already saw our use effect takes two things one a call back function and other is a dependency array so I'll just say effect or you can call it call back CB effect whatever I'm calling it effect and dependencies or just I can say depths now let's see what are all the cases that we have to handle handle over here first of all we have to handle the first render case then we have to handle what happens if the dependencies changes and the third case is the cleanup also dependency changes and no dependency array both of the cases right so okay let's handle our first Ender case first so for this I'm going to take a use ref hook and I'll just say is first render now you might be thinking why have I taken a US ref hook over here so I'll just keep it true by default so the reason why I've taken this user F because user F the value of user F persists even through rerenders of the component so let me show you let me just first import it in this first render I will simply say if is first strander do current that is if this is true so to access this value over here we use dot current after the variable of us ref I'm just going to say is first render do current equals false this will become false now and I'm going to Simply invoke our call back and return we don't need to do anything else we don't need to go forward and execute this hook anymore we just simply going to return because that is all we needed to do in the first render and now even if this custom use effect even if our component renders and it still reinitializes this use custom effect hook this value will persist throughout the reenders so that is why that is the reason why we have taken use ref over here if we would have taken use State over here whenever our component would have rendered and this would have been reinitialized in our component this value would have been lost and we would have initialized it back to true so we we won't be able to track if it's a first Ender or a second render now we need to check if our dependencies have changed or we have no dependency areay at all all so for that as well I'm going to take another us ref over here and I'm going to call it preious dependency so prev depths and by default it's going to be empty because our dependency array is is basically an array right so that is why for previous dependencies as well I'm going to take an empty array over here so cool let's think of a condition so const depths changed equals so how do we check if the dependencies have changed or first first thing first we need to check if we have a dependency array or not so depths so this depths over here if depths exist do something else just say true this true case will be useful for us when there is no dependency array and we need to render it every single time so I'm going to get back to that later right now let's see this condition if dependency array exists then we need to compare it with our previous dependencies so how do we compare this json. stringify depths I'm going to stringify it and I'm going to compare if it's not equals to json. stringify previous depths let me just close this previous depths dot current that is this one over here right so that is what we're doing over here we're stringifying it and then comparing it that is the dependencies have changed then I'm going to say if depths changed so invoked our effect hook now notice this will be invoked only in two cases either dependencies have changed or there is no dependency array provided to us so as we already saw that is what use effect Hook is all about right and in the end I'm I'm not writing this cleanup right now now I'm going to write it after some time let me just uh do previous depths dot current equals whatever the current dependencies are so I'm just going to assign this depths or if there is no dependencies at all I'm just going to keep it empty array as before so cool let's let's go on and try to use this so let's export this export default use custom effect right let's go on over here and I'm going to import it from our hooks let's save this and finger across let's see if it works or not all right so let me just uh refresh this page and see let me just remove this cleanup it's not going to work right now now refreshing this again okay so our dependency array was empty so our effect was triggered for the very first time let's try to increment it okay increment decrement our component is rendering but our use effect is not getting called so our first case is managed over here awesome let's manage our second case that is when we enter count it should change when the count changes so okay if I increment okay this is working as well if I enter some other state which is not changing let's see if it gets triggered then or not okay it's not getting triggered that's good as well if I get rid of this all together what's going to happen it should now get rendered every single time even though the count is not here or count one is not here so awesome it's still working the same great all right now let's take care of our cleanup functionality for our use effect polyfill so when does our cleanup function runs as I already discussed it runs either when the dependency array changes or when the component gets unmounted so obviously we can't really simulate the functionality of component unmount because that is something that react does under the hood by using its fiber tree algorithm and a process called reconciliation which manages the component life cycle including handling effects and cleanup during unmounting but we what we can Implement is invoking the cleanup function when the dependency array changes all right so let's go back to our use custom effect over here first of all in our first render so if we are doing something like this um if we are returning during our cleanup so obviously we will return this function from here so inide of this in our very first render I'm going to receive it so const clean up equals effect and over here I'm going to check so inside of this return actually I'm going to check if cleanup is there and cleanup is equals to a function then simply invoke it for the very first time and the second case is going to be over here so if our dependency changes obviously I'm going to do the same thing I'm going to take it inside of this variable now I'm going to test uh let me just copy this condition as well I'm going to check over here if cleanup is there and cleanup is equals to a function and we have our dependencies so depths only in that case invoke it so obviously see if the dependencies doesn't exist this will run every single time right but we don't want to invoke it if there is no dependency array so we're only going to invoke it when our dependencies changes also I made a mistake over here this is going to be type of so if the type of cleanup is function and over here as well type of cleanup is function only then we're going to invoke it all right let's go back to our counter and try to test this so if our dependency array changes now so count and if I click on increment decrement yep you see our cleanup is getting rendered every single time but what if it this is empty clean on increment increment okay this is not getting triggered awesome so this is how you implement the cleanup functionality as well if you like this video you can access more such videos like this by clicking on this card above my head and accessing the complete react interview questions playlist
Info
Channel: RoadsideCoder
Views: 14,690
Rating: undefined out of 5
Keywords: useeffect hook in react, react useeffect, useeffect react, how useeffect works, react interview, react interview questions and answers, react interview questions, frontend interview questions, javascript interview questions and answers, javascript interview questions, javascript interview questions and answers for experienced, web developer interview questions and answers, javascript interview, reactjs interview questions, reactjs interview, Namaste javascript, namaste react
Id: tNQuUgmv1Fs
Channel Id: undefined
Length: 20min 27sec (1227 seconds)
Published: Sun Dec 17 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.