useEffect and useLayoutEffect | React Hooks | React.js Tutorial #6

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello youtube today we are going to have a look into the use effect hook and also the use layout effect you might now be asking one of two questions what is the use effect hook or in other words when should i use the use effect hook in my react applications so reading the react documentation we can find the following the effect took lets you perform side effects in function components but if you don't know what side effects are you might be asking now another question so i will try to answer you a side effect is any application state change that is observable from outside the function you called probably this doesn't mean much so let's put some code into the picture let's say that we have these add numbers function and in the second line of our function we have this window.variable equals to result so every time we run this addnumbers function if someone from the outside does window.variable they will be able to see that this state changes every time the add numbers is called so add numbers is performing a side effect of changing this global variable value that's a side effect if another function call these add numbers that function itself will have a side effect not directly that's true but indirectly it has a side effect because it's calling the add numbers now let me give you another example that is still a side effect we are changing something directly into the dom so our users will be able to see that every time add numbers runs it will change something that our users are seeing so that's a different type of side effect but it's also a side effect by having this as an example you can probably think that the console log that you use quite a lot if you do console.log.bruno that is also a side effect if someone has the developer tools open in the console they will see bruno being printed so we are changing state that is visible from the outside of that function once again the same will apply to for example http calls to your server if you are using for example web sockets you will open and close the web sockets inside the use effect hook so now that you have a better understanding of what the use effect hook should be used for and what side effects are let's see the first code using a use effect so over here you can see this use effect and now we are passing a function inside our use effect the code internally that function is not that important the only thing i want you to focus right now is we have the use effect we call the use effect and pass a function into it right so what is the intentions that we have as a developer let's just simplify this code a little bit and see what are our intentions well the first intention if this component is being rendered with the name of bruno our first intention is that our users will have a div with bruno into their screen sooner or later right that's the first intention you have as a developer that build this screen so this is our first intention the second intention is that sooner or later react will be able to run our function and say on the console bruno that's the second intention we have so let's now jump into the timeline in order to understand what happens after the moment that react calls our component with bruno so over here this is the moment that react called our component our component executes and we'll return that div with bruno inside and also the use effect but these effect react we'll keep it over here for now right we will pick it in a second so right now react will look into our div bruno and say oh okay i need to transform the dom in order to have this div with bruno so react starts those dump changes and it will look something like this if you open the developer tools right at this moment our browser didn't have yet the chance to do what we call the browser painting okay so you will see on your browser just white for this second okay now your browser will yes have a chance to paint and when your browser paints it will translate whatever we have over there into pixels so you will be now able to see bruno in your screen now yes now react knows that the browser painted so i go into my effect and i will run this function that was passed to my effect so our function will run and it will say to the console bruno into the console right so this was the timeline for the use effect and this is very very good you can see that the use effect code is offloaded to after the browser paints and this will help you improve some metrics for example the first meaningful points that you will see into some lighthouse metrics if you run the profiling okay now there are use cases where you don't want to run after the browser painting they are very small and very few but they exist so when you have code like this document.queryselectordiv dot style dot background equals to red if our effect was dead then after our effect runs we will have another browser painting over there and we will end up with bruno with a background color of wrap but this is usually not ideal for our users because they saw a blank screen then they see bruno and then they see the background changing to rev in this specific example because we have so little dom elements it will be completely okay you will not see any flickering and probably you don't even see this middle one because it's so fast that you don't have a chance to see it but when you start to have a really big application this type of scenarios will give you what we call the flickering so your screen will do some type of flickering and it's very annoying as a user experience so you want to eliminate that middle state of your ui and for that you want something that allows you to run your use effect before the browser paints and for that we have the use layout effect so let's jump into the next screen because this one is getting a bit too messy and just look into the use layout effect after the moment that our react does the dom changes so if we are over here right now if we are using use layout effect it will run immediately after the dom changes from react synchronously immediately after so when it runs it will now change our html or our dom to have that style with a color of red and only after it will give the chance for the browser to paint so now when our browser paints you will have no middle states with bruno with the background color of white you go immediately from a white screen to a screen with bruno with the background color of red this is very important that we have those two in react the use effect offloads a lot of important stuff to after the browser paints so it will help us in some metrics like the first meaningful point the more we can remove from the browser points right every the less code we have before the browser paints the better and so use effect is what we will use the most but some use cases like this one i showed to you the use layout effect is quite effective so now you have the knowledge to decide which one you need depending of the occasion you have in your application and without much more talk let's now jump into visual studio code where i will show you how to perform an http call using the use effect hook over here we have the same counter component we created in our last video for the use state you can see that we still have the description as a property of our counter and we have the buttons to decrease and increase our counter so if i click there it increases it decreases i can do bruno one two three four and it still shows the result over there so let's say that now i ask you for a new feature over here i ask you every time that description changes i want to do a console log of description so you will be tempted to do something like this use effect and now you pass a function into it and do console log of description right that will be probably your first try if we go into our developer tools and i do 1 2 3 4 it seems to be working but now every time that something else in my component changes and forces it to re-render it prints once again and once again and once again and once again right so what's happening over here what's happening is that every time that our component re-renders because description changed or because the count value changed we are still creating a function and because we don't have any dependency array over here react after the browser paints the new changes we'll just call our function over here so even if the value didn't change react just calls our function we have a console logof description so it just shows what it shows right now if we just want this function to be executed every time description changes we can pass a second parameter to our use effect and that parameter will be an array of dependencies in this case the only dependence we have is the description itself so if i come over here and i refresh this page you can see i do one two three four and i still printed that but now i can do whatever i want in any other property of my component doesn't matter how many times our component re-renders react will check the last value of description was for example bruno now the value is still bruno so doesn't call our function but if the new value is for example bruno 1 then yes it calls the function because it's a different value right and this is very important for us when we are using the use effect otherwise we will be having this function being called a lot of times and most of them will be useless right so now that you know that let's say that you are doing an http call and that http call is taking for example three seconds so we can simulate that before we do a real http call with a set timeout right so let's just do a set timeout and simulate that this http call is taking three seconds for example so let's move this console log inside the set timeout and if we run this code now let's see what happens i will run the code and i will do one two three four we wait for three seconds and then it will start to show all the values that we had before right so this is exactly what happened in the previous video our component renders we create this function and at the time we created this function the value was for example bruno so whenever the set timeout is finalized it will print bruno then this component was called with bruno one which is this second render so when this function is created the value encapsulated there it will be description as bruno one so when it prints it will bring bruno one and well it will do the same thing up to bruno one two three four if for some reason you don't want this to happen and you only want the last one right because sometimes if it's just intermediate stuff that is not finalized you probably don't care about it they use effect hook has something for us that very useful which is a cleanup function we can return a function over here you can return as a arrow function you can return as a normal function like this right usually i like to call this function whatever i'm doing over here in this case i'm just just stopping um the set time out or clearing the interval so i will call that clean the interval from set timeouts right you can call it something else and now what we want to do is because this is a a render that didn't finalized yet we create the set timeout for in three seconds so if a new render starts this function will be called before that new render starts so in this case i just want to cancel that set timeout luckily set timeout returns the id of this timeout so we can just come over here and do clear interval oops clear interval of my id doing this now when the new render starts the previous one we'll call this function calling this function we cancel that interval that interval is gone so i can now come over here refresh do one two three four five six and now only the last one will be printed into my console if i keep typing and i do 5 6 again only the last one will be once again printed into my console right so if there are any intermittent or in the middle set timeouts waiting we just cancel the ones that are still waiting right that might be useful especially if you want to abort http calls for your server so now let's say that you were using something else uh that doesn't give you this id for you to cancel and that might happen uh when you don't control the code you are calling so let's say that you want to execute the same type of thing but without having that id in order to clear the timeout so you will see this pattern from time to time and you create a new variable over here people that are coming from react using classes they will call it mounted equals to true for you you can call it the current render or something like that right so i will explain to you what's happening you will call it current render for example and you will say true so if for some reason react starts a new render now in our destruction or in our cleanup function so let's just do this in our cleanup function we can just say okay current render equals to false because we are starting a new render so whenever this set timeout fires we can look into that current render we see oh the current render is false so we don't do a console log let me just come over here and do current render equals to false and now you just need to do something like this current render right so if it is the current render you do the console log i can even do an else for you to see what's happening so i can do console log of oops i am done or in this case i am the past right not done but the past so i can now refresh if i do one two three four you will see oops i am done it will be printed four times and then the last time we will print the value inside the current render this might be you very useful when you don't control the libraries that you are calling and they just have a callback or something like that right this is very very useful so i will just now do a commit for my repository for you to also have this bit of code right i will do a commit and then i will come back to show you how we can do dhtp calls i already committed our changes and you can see them into this commit the set timeout examples if you click on this icon it will navigate to that moment in time you can then click on source come to counter and you will see that i committed both versions the version with the clear timeout and the version that i was using the current render with the if else logic and this if else logic might be useful for you to also do in http calls but in reality i will recommend you to use something like swr even though i will show you how you can do a simple http call using the use effect so for that we will come to jsonplaceholder over here and if you scroll to the bottom and run this script you will see that doing this http call it will return this json over here so let's copy this bit over there open our vs code let me just also open my browser and we will do the following asynchronous function load data and over here we will put that bit now i can do cost response equals to a weight of our fetch and then i just need to do const json equals to a weight response.json right this is usually a very simple http call when we are using the use effect in react you can now open our development tools and when i clear this you will see that nothing is happening and why because i forgot to call this load data so we need to call that load data now yes now if i just refresh this you will see that i'm doing this console log of the asd isd i can just pass the json and you will see that i have it over there what if i want to now change it to for example whatever value is in description right you will see that when i save i will have a 404 because it doesn't exist but then if i put for example 12 i'm getting the id 12 over here which is exactly what we want now let me just create something over here called to do set to do equals to use state and now i will just do set to do instead of doing the console log i will do the set to do as jason right and now i'll i will put for example in my jsx over here i will do to do dot but now we don't have types yet so let's come back to our json placeholder website copy this json bit over there come to a website called json2ts and this website is just magic and save me so much time so now you click on generate typescript and you will see that from any json you put over there it will generate interfaces for you so we just need to copy this interface over there now come into our vs code and now paste this interface oops not that place this interface over there i will call it to do and now i just need to use the generics on my use state to pass the to-do over there so you can see that now it can be a to-do or undefined i come over here do a control space once again i do enter and now i have the title typescript already knows that it might be undefined so it's protecting us as well i come over here and now when i put 12 i'm receiving the title of my 12 i can put 1 to 3 and i'm receiving the title from 1 to 3. this is very very nice right so what what can we do apart from it we can now if you want to start to do the validations for for example when i have bruno you will get a 404 you have an exception you can start to put a try catch over there and then also on this set to do you will have the problem that you can do an http call now that will take let's say 30 seconds to complete this is bad but let's say 30 seconds to complete and you do another one over here so you would want to ignore the first one but if this one is started here and finishes immediately here if that one is only finishing immediately over there you will be setting a to do for the old one so you will probably want to do again that boolean trick that we did before in order to if it's not the current render just don't set it up i will do a comment on my repository with that but i will leave that as homework for you and also if you really see yourself doing this quite a lot please don't do this do this as an exercise but don't do this in a real application in a real application you probably want to use something like swr or react query right i will leave a link into the description and also probably in a card over there to a video we already have on the channel about swr that will do all of this code we have over here in a single line swr will look something like this like data loading error equals to use oops use swr and then the http slash www whatever so all that we have over here will be done over here with only one line plus it will give you caching it will do a lot of benefits for you like the error handling and all of those things so i will leave that link in the description and in a card so i hope you enjoyed this one if you did like the video subscribe to the channel and if you want to do the exercise i left to you go into my github repository and see my last commit uh where i'm doing that mounting and doing the e-files to not use uh the latest set to do but the latest that was called alright so i hope to see you in the next video about uh the use memo and we will do memoization in react so i hope to see you there and bye bye
Info
Channel: Bruno Antunes
Views: 6,511
Rating: undefined out of 5
Keywords: useEffect, react hooks useState, react hooks, react.js hooks, react.js useEffect, react useLayoutEffect, react.js hooks typescript, react hooks typescript, react hooks typescript useState, react use effect, react useeffect, reactjs useEffect, react js useEffect, react js hooks, useEffect hooks, hooks useeffect, hooks effect, functional components effect, react function components state, useLayoutEffect, react side effects, react.js side-effects, side effects react js
Id: R6zvdn40VfQ
Channel Id: undefined
Length: 22min 50sec (1370 seconds)
Published: Mon Oct 26 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.