React Hooks Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
so this video is my entire react hooks course compiled into a single video so it's gonna be going over the following hooks and it's just gonna run back to back to back now if you want to below I'm gonna put links to each one of the individual hooks if you're interested in just a single hook otherwise stay tuned to watch the entire video where we go through all the hooks so this is the beginning of my react hook series we're gonna be going one-by-one through each hook and explaining not only how to use it but why you might want to and some of the advantages they have over class components in this video we're gonna be going over the use state hook now if you want to follow along I'm gonna be using create react apps I recommend in your terminal go ahead and run this command MPX create react app and then the name of your project so I ran this command and I have the project up here and I have app dot J s open and I just cleaned up some of the cruft now I'm gonna go ahead and just do yarn start to run this project and just have it running in the background as we do stuff alright so the first thing that I wanted to go over is with hooks is that we now need to only use these with or we can only use these with functions we cannot use them with class components so we can either write a function like so or you can write a function like this either one works you can use arrow functions or regular functions you can both use hooks inside of them it is just comes down to preference the next thing you know you can put these settings inside of functions but there's some rules around them I'll link this below all the rules and you can read through them but these are the main ones here and basically you can't nest hooks inside of loops conditions or functions now the nice thing about this is they have some es lint rules for this so it's gonna actually tell us when we do stuff wrong because we have well you're gonna need an es lint via scope plug and I believe to see it in here but also it's gonna be caught by create react app so what I mean by that so I can say if true use state or say react you state alright so this is the you state hook that I'm just calling right here notice we got red squiggly you see you'll get this if you have es lint configured and you have it the plugin and BS code can hover over this and I can see react hooks is called conditionally react Chuck's must be called in the exact same order and every component render so basically cannot nested if statements and all that jazz and I think if I come over here it's saved we should also see it you also get these warnings in your browser as well if you don't have the vyas code extension okay so those are the rules around hooks let's go ahead and dig into this you state so I have it I'm just calling it like this I can also call it D structure up here you state I'm just a little cleaner call right there so this is what we're gonna use now this is the replacement for state for class components we use this thing called use state so here we can call as our first parameter the initial value that's gonna store so for example I can say the initial value should be as 10 and I can also if I want to have a function that returns the initial value so the reason why you may want to do this is if you have a computation that's really expensive so if we have like a function up here that's like expensive initial State you know and it does something like for example it does a bunch of for loops or whatever you may want to call it like this and that way this is only called on the first time and not on every single time that component renders so that's good to note you can basically only have this run on the initial value alright so this is gonna return an array and you're never gonna see people actually do it like this you're gonna see every one D structure the array like this and the first value is the value of the state so here I can say you can call it count let's do a counter that's a good first example and the second value is a function that lets you update the count usually people call it set count or whatever the name of it is and just for simplicity sake let's go back to just using ten here so here we're gonna render counts and then we're also gonna have a button here the press and then we can update our account alright button plus on click and here we're going to say set count and we can say count plus 1 so we're using the value here and then we're incrementing it all right and we can plus and we can see it increments and that is how we're storing the state for this counter the other good thing you should know about set count is similar to set state you can actually pass in a function to this so instead of grabbing count from up here I can pass in an update or function so what update error function is it's gonna take a single parameter and you can take and this is what the current state is so in this case count I could also name this current count and I can say here we want to return the new the new state so I'm saying the current count plus one alright so we'll give that a save so this is a good idea to use this to avoid kind of like race condition things and having two updates happen at the same time and the updates get overwritten but anyway that's the side note so those are the two ways you can call set count here and it's gonna work exactly the same way just incrementing the count there so those are set count the other good thing to know about to use state is it works slightly different than set state so let's say we have count in here which is 10 and so I'm now going to D structure this to have count there we have set count here and I want another value in here which is called like count 2 so we're just gonna be real basic and that's gonna be 20 so now let's say I want to increment the count here but I only want to increment count 2 so I'm going to say count one count two and lets destructor count do so again you can pretty much store anything you want in here so we are now storing object and here I'm destructuring that object grabbing the counts and I don't know why I went back over there this is this update function now needs to be fixed so here we can say the okay call it state it gets to call it current state this is now an object so what we can do if we want to increase a new count to say current state count plus 1 now if you're used to this dot set state in class components you'll know that this update will happen and this count to value won't change buttonhooks it's a little bit different as we see when I increment this this value disappeared and that's because it does not do any merging of the objects all it does is it takes this value and sets it as its state meaning if you want to keep any of the other values that are inside of the object you have to do dot dot dot current state right you have to keep all the values that it were in this state beforehand all right so do I just kill it oh yeah because I need to put this up here there we go because what I need I'm putting the value of count and count two into the object and then I want to overwrite the count value and now 20 stays there I could also if you don't want to use dot dot syntax you can see this as count two is now equal to current state count so basically if you store an object and use state here note that you will need to whenever you update it provide all the keys the other thing about you state is you can use multiple these things so there's no reason why we can't just say instead of using an object here break these up alright so I'm gonna do count and count to do 20 so you can have as many you States as you want up here so I have one for the value 10 one for the value 20 and this is the set count and so this simplifies things so now when I call set count all I need to return is a new new value for the first count here and this just won't change count two over here all right just doesn't affect it so if I wanted to increment both of them when I hit the plus give a save I can say set count and insect count to alright and yep we can use a exact same update or function there and that should work so now you have kind of a little bit of a decision whether you should split things out into multiple you States or you should use a single use state and use an object in general what I do is if I'm going to update both values at the same time like I am here I'll usually combine them into an object if I'm only calling one at a time I'll usually split them up all right so that's kind of the basics of use state I kind of want to now go into why does anyone care about this why are these you state hooks useful and it really comes in to defining your own custom logic and being able to extract this logic in the hook and use it all over the place so one thing you made be doing in your application a ton is forms so we're gonna take a look at a form example so I'll get rid of these counts and we're gonna create an input field here and we're gonna display an email and a password and we're gonna say type password all right and we'll get rid of the button so to basically represent this form I could have a email and a password and I could say set email and set password and they're going to default to MP strings and then I'm meseta value is equal to email and then on change I get the event and I say set email is equal to the event target value and I can copy this logic and I could put on the password but this I'm gonna call set password right and we could do this for all this fields but if you've used and we should set the value here so if you're familiar with react we don't have to do this and this is kind of time-consuming for each field but here we can come in here and type some stuff in and we can see the values so cool so how can we do this in a better way well we can extract these hooks into our own custom hook which handles the state for us so we're gonna create a new hook over here which I'm going to call use form dot J s so you'll notice the syntax for hooks is you have the use in front or the naming convention I should say as you say use and then whatever it is so use form because the form state is what I'm storing here let me say export Const use form and so this is my own custom hook and this is where things get cool so now I can put stuff inside of here for example hooks so I'm gonna stick this over here and now instead of storing it like this I'm gonna store a little bit differently so here I'm going to say initial values and we're gonna store the initial values in the state here I also need to import this well let me auto import it no it won't shame import from react alright so the initial values we get here so these are some form values I'm gonna call them values and we can say that call this set values here so now I can return some stuff from my hooks first I'm gonna return the values here you'll notice also I'm choosing the return object here this is just preference you could also return an array if you wanted to and match the syntax of you state this really just up to you and maybe we can do that just to show you both ways so we have values here and then let's say we want to pass in an unchanged function and that way we can get handle it for us so here I'm gonna say E and what we're gonna do is we're gonna say set values and we're going to keep all the values inside of there and then we're going to say e dot target dot name is equal to e dot target dot value so basically based on the name of the input field we'll update the value of that value in the form alright so now we can use this use form hook over here so now I'm going to say use form and the initial values for this I'm going to say email is an empty string and password just an empty string and then here I have values and I have handle change so now I can say values email values not password and for the on change here I can say handle change and handle change here and it's going to update based on the names that I have here so I can come over here it can type some stuff and it works just fine now and so we were able to encapsulate that logic inside of this little function that I made here and so now I can use this function or use my hook in other components and it has no UI associated to it all it has is logic right and the logic of how we want to store State and so that is pretty cool and that is really the big advantage with hooks and so now we don't have to use a rendered what's it called the thing where you do like for example a former library and I wrap it like this so again this kind of hook you would ideally use oh this should be it seems to be a fragment again this may be a hook that you get from a form library but it's good to know how this works and it's good to know that we can now use hooks like this instead of using rendered props like this so I usually use formic performs and it'll usually look like this and now I don't have to do that especially gets ugly when I have multiple of these and I have like maybe you know some some rendered props nests inside of them so this is where hooks shine and we can easily have two forms here and the it doesn't get real ugly values to handle change too and maybe this is first-name lastname again I don't know why you'd want to do two forms like that we could just mash them into one but you get the idea we can have tons of hooks just sitting up here and then we can create our own custom hooks and put the logic and reuse that and not have to share any kind of the UI of what it looks like it's very easy to share the logic so there you go that is you state and why it is useful in the next video we're gonna take a look at use effect so we're gonna be taking a look at the use effect hook this one is very useful a lot of situations but it can be kind of tricky to get used to so we're gonna start off with a basic example and our worker way up in complexity so in our application here I'm going to say use state or I mean use effect and I'm going to pass a function inside of it and let's go ahead and import it up here so the basic usage of use effect is every time this component re-renders or is rendered this function will get called so we can see that if we had a console log here and say it render and now if we go over to our code you can see it's rendered once and as I type in this it's gonna render a bunch type in this it's gonna render even more now everything on top of this is basically ways to get this to render less and to clean up after a render has happened so if you want stuff to be called less and by I don't mean render less I mean for this function to be called less so for example what if I don't want this to be called on every render I only wanted to be called whenever I change the password we can do it like so we can say comma and then pass a array here and we can say values password so now whenever I change the password this render console.log is going to fire off so here initially it's gonna fire off as well so whenever I make a change see a render changes if I change the email this does not change so what did I just do well the second parameter here is called the dependency array that you can pass in and so here you can pass in all the values that your effect depends on and so these values whenever they change the effect fires off again and so that's the gist of it and we can put more than one if we want to in this case we have only two values but we could add another one here let's do first name first name first name values dot first name anger that a save and I can say values dot password and values email so now my effect depends on the email and the password but not the first name and I need placeholders so placeholder first name alright so we see it we see the functions getting called functions getting called functions now not getting called now the thing to note about this is this is doing a shallow comparison of the values and whenever the values change this is going to be recalled now by shallow comparison I mean if we were to put something like this object here the object is going to change on every single render the reference anyway or new object is going to be created so it's going to be called every single time in a future video we're going to cover how we can avoid such problems like this and I'm also going to link to a video that I did about problems you may occur with use effect with closures it's more of an advanced topic that you may want to hit later on and also a great article by Dan about use affect all right so that's that the next thing to note about use effect is you can kind of replace component did amount and component will unmount with this so if we don't pass in any values to use effect here we can now have this console.log once when it mounts and that's it so doing renders not going to recall that function there and I can do a clean up function which means we return that function from the inside of the function here and this is the called the clean up function and so i've here we can add all our clean up logic and this is going to unmount we can't really see this because it's gonna like happen like when the component disappears but if i were to create say another component here called hello GS and in this component if we toggled it if we showed it and then didn't show it we couldn't see it unmount and remount each time alright so let's copy this over export Const hello and we're just a div hello and we can just say react out use effect and here i'm going to say hello we're gonna say show hello set hello set show hello and we're gonna say you state and by default we will show it so here I'm gonna wrap this and conditionally render hello so show hello and then we are gonna toggle it on and off and we're gonna gate it so now we can see that this has rendered and if I were to toggle it and it disappears you'll notice the unmount is called pull it on you can see it render and unmount again so we can see the component mounting and unmounting and those two console logs go off and we could see that happening now the cool thing about this is it doesn't just have to be when when it it mounts and unmount so what do I mean by that well if we go back to our example over there you can ignore hello again by the way if you don't know how to comment out blocks like I'm doing this might be hard to follow so command and then slash is how you do that probably control slash on Windows so if we go back to our use affect here let's say I want this to fire off whenever values dot email changes well whenever values are the email changes or we get it's gonna clean up it's gonna call this clean up function alright so we render I press a you see it's going to unmount we're not really unmounting we're just cleaning up the old value and then we have a new value here so that's pretty cool so that's pretty powerful that we can do that not just on mount and unmount we can do it whenever the dependencies change we can clean up anything we need to with the old stuff okay so these are kind of some basic examples and the basic fundamentals now I thought would be good to show you some use cases of this and regular apps so the first thing I want Gover was with events so for example I may want to add eventlistener so we're gonna do Mouse move and this is a nice one because when this mounts I want to start listening to the mouse and basically what I want to do is just display the current location of the mouse so I'm gonna say Const on mouse move and just to start I'm gonna console.log the event here and so I can pass in on mouse move and then I want to clean up this function when I'm done I can say window dot remove event listener mouse move on mouse move so it's pretty nice that we can use this use effect here and we can have this when it first mounts add it and went unmount so clean it up by removing this another thing I haven't mentioned yet but I guess I'll mention it after we show this real quick so we can see as I move my mouse around we can see all these console logs of the values updating so effects are a great place to add event listeners and remove them and I didn't think any worry about showing the value on the screen this gives you the gist of it but what I wanted to show you was you can have more than one use effect on your component and they fire off in order all right so this is going to be mount one and then mount two and again you can have as many use of X as you want could see one - they fire one and after the other all right so the next one that I wanted to do is to fetch from an API so the API manifest from is the numbers API so I'm going to copy this URL so here we just pass in a number and this is going to give us access to a fact about that number so we're gonna create a custom hook for this I'm gonna call it the use fetch hook I'm gonna say export kant's use fetch and what this is going to take is a URL so I'm actually just going to paste this over here and I'm gonna get rid of some of the stuff we don't really need these anymore so the first thing that we want to do is we want to whenever this URL changes you want to fetch some data so we're gonna say use effect dang it we don't get auto completion JavaScript for this that's sad all right use effect so I'm gonna add the URL as a dependency so this function is going to be called whenever the URL changes so here is where I'm gonna call fetch and I'm going to pass in the URL now this is going to usually if I was writing this I would make this asynchronous but BAM we're already getting an es Lent warning here it tells us that you need to return I was just telling you it's not exhaustive I'm surprised the sealant warnings coming up and probably it shows a good example here it says a wait there anyway the point where I was trying to make here is you can't put a sink right here in the function and use a wait it doesn't like it so we're not going to do it like that we're just gonna call fetch and we can do dot then we could also have a function in here that we make asynchronous and then it can call like that so it's up to you you have those two choices of how you want to do it I'm just gonna do dot dot then syntax all right so we're gonna fetch from the URL and I'm going to say X dot now usually I would say X dot JSON but this particular API is dot txt so dot txt and we're gonna say dot then and why don't we just console.log why so we see that the value is actually is what it is and so I'm just gonna call her our hook real quick so we're gonna say Const and does it return anything yet so we're just gonna say use fetch I'm gonna pass in our URL dang it there we go so here we can see our fact getting logged logged out here nice so let's make this more useful so I want this to basically a return to me the data and a true or false whether the data is loading whether there's anything in the data so how can we do that well we can combine this with you state to store some information so this is where you're gonna see we can kind of use multiple hooks here in our custom hook so I'm going to say set I don't know what I want to call this we'll call it set data so it's gonna have data inside of here which is gonna be null by default and loading which is going to be false and we're gonna return I guess maybe we want this to be true by default and we're gonna return data this is kind of bad naming convention cuz data data here maybe I should call this state and we'll call it set state all right so here we want to say set state the data is equal to Y and loading is equal to false and then at the very start here I want to say set state data is null and loading is true so at the beginning we're gonna set loading to true and then we're gonna fetch the result when it comes in we're gonna say passing the data and loading is false so now here I can display this I can say just do at the top you could say if we're loading we're gonna say dot that thought otherwise we're gonna display the data in this case it's going to be a string and here we can see that it's playing nicely there and now the next thing they want to do is I want this URL to change whenever I or the data change whatever this URL changes so what I can do is I can add a little counter so we can say count set count good start at 0 and we can say div count is equal to count you can say increment and so now we're going to get a new fact every time I increment the counter so we can use the updater function here for our set counts and then this is what's going to change so now here is going to be the current count all right so zero is the atomic number we increment we get a 1 and we can see it populate here now I think what's happening is you saw though there's like a little bit of a jitter I think it's cuz we're displaying loading so maybe we want to say if there's data there's not data display loading otherwise that get me get a little smoother no oh you know is it it resets the data every time right here so maybe we can get it this even smoother we can say state data so if we currently have data we can pass it in there all right so now we have a little bit smoother of transition but there we go notice how every time I increment this looks like a bad gateway 10 looks like we hit a problem the API maybe we're making too many requests but either way we've made 10 requests every time we increment the counter is going to update the state here and it's passing that value to our use fetch which is updating these values so we're starting to see where this can be kind of fun and kind of useful at this now a few things I wanted to note about this use fetch first let's say I didn't include this URL then this would not you know be called every time the URL changes but you'll notice we have this nice little warning from es Lent for us the exhaustive dependencies because it sees that we're using the URL here but we didn't include it here so you may notice that you're gonna be getting that and that's a nice little reminder to add those in here the other thing is you notice how I'm using set state here I should probably add set state to the dependencies so yes you can add dependencies functions as dependencies and you probably should be and again that's where you have to be careful the function is changing every time the other thing to note is you can infinitely recur if will infinitely just call each other is if you call set state here and this triggers this to change so you can just have it infinitely call at each other and the fact keeps game calling so you have to be very careful about that as well so make sure your dependencies are not changing based on what the user fact call is at least not over and over alright so that is the use fetch the next thing that I wanted to go over last thing is a saving the state so I found a hook very nice to do this is for example if I want to persist this to say local storage so I can make a user fact hook here and so let's say I want to persist the value of count so here I can say I want this function to be called it every time the count changes and I can say a local storage dot set item dang it mariel local storage and here I can say key I'm just gonna call it count and I'm gonna say JSON a string of five account in case I ever want to change the count to something else beside the number later for some reason and yeah it's as easy as that so now every time the count changes its going to set the count in local storage and now I can change the initial value of the count here by saying local storage get item count and we can do a json dot parse and again we just have a single value of account but this algorithm would work for say objects in raise as well since we're using parse and string if i now I don't want json.parse and local storage dot get item to be called on every single render so this is a good opportunity for us to use the initializer function of U state alright so let's see this in action and see if this works so we're going to refresh here I'm going to increment this to three and we do a refresh and you notice the value of three is there so again every time I increment here it is updating the count in local storage and then when we reset or refresh is eating that value with this initializer function here so there you go that is kind of an introduction to use effect and some of the things that you can do with it that are pretty useful as you can see it has a little bit more flexibility than what you had with the class components it's kind of a new way to think about calling your data and combining these things together and we can undo all kinds of change logic together and we can multiple use effects because right now we have this use of fetch or use fetch which has use effect in it and then we have this other use effect at the bottom here we could also be say for example caching data that we're getting from use fetch if we want to and do all kinds of stuff but that just gives you a little introduction to this and I hope that was helpful so we're gonna be taking a look at the use ref hook now this one we're gonna start with the most obvious use case which is storing a reference to a component say an input field or div or something and then being able to reference that node in your application so for example what we're going to do is I'm gonna make a button and whenever I click the button it's going to focus the input field here and so we can use a reference for that and then we're going into some of the other use cases you can use user f4 alright so let's start with the thing that you're going to use it pretty much the most for so I'm gonna say Const input ref so we're going to create a new variable and I'm gonna say user ref here so this is our new hook and I'm gonna say use ref and import it from react so now what I do with this is I can pass this to whatever component I want to get the reference of it so in case my input field here and this works pretty much the same as create reference if you're used to class components that react so I pass it in here and then I have reference to this input field now so what I can do you have a button that says focus and we're do on click and I'm just going to start by logging what the input ref is now you'll notice we have to say dot current to get the current value of the reference so I'm going to say click and you can see I have reference to the input Dom node if you will and we can do whatever we want with that we could call any methods on there or read the values of stuff what I'm going to do is I'm going to say dot focus on it and so I'm gonna come over here and when I hit focus you see my input field is focused over here so that's the main use case I'd say for user F or the one that I used most is getting reference to some kind of react component and then being able to use that somewhere in my application where I need to lie comparitively call stuff and this will not cause a rerender for example just focus or if we need to do any getting value like get the bounding get bounding rectangle I think I forget the name of it we're not gonna be able to call it but you can do all kinds of stuff with that the next thing I want to go over is and I just keep the dot focus there is the other stuff you can use the reference for this is basically anything you want to store a reference to it doesn't have to be a Dom node or a react component I guess we can store for example integers in here so what I'm going to do another use case I use for it is to store the number of times a component has rendered so while we do this for the Hello component let's bring this back so I'm gonna say renders and I'm gonna store a integer inside of this reference so let's import it and then all I'm going to do is just console.log and I'm going to say hello renders and I'm gonna say this will just render I mean just say dot current to get reference to the zero there this is just gonna render zero every single time what I'm going to add is plus plus so increments every time the console.log is shown now the thing about this current is we can update the value of it whenever we want to it's not going to cause a rerender so if you were to have like instant variables on your classes this is the same use case you can put stuff on there like that which is not tied to react tree rendering for example instead of putting in your state you can store in a broth if you want to all right so let's just uncomment this right here oops and take a look at that all right I need to just uncomment these one at a time I think there we go let's add a show hello back and we're gonna say you state true all right so you can clear all this stuff and of course as I'm typing here we can see how many times Hello is rendered we can toggle it off it's gone tall it back and three starts there and again we can sort everyone this so it doesn't have to just be numbers it can be objects it can be functions whatever we like so another use case that I use for this is with use fetch so it's helpful to know whether a component has unmounted and so we can prevent an error when we try setting state on a component that is has been unmounted so what do I mean by that well let's basically cause an error real quick so I'm gonna move the logic of calling the API and displaying the numbers over here I'm gonna move it over to our hello example so I'm gonna just move this right here and copy this all over and let's import use state use effect and we can import our use fetch and I'm going to just bring that over to my hello example dang it I undo copy again okay so now I'm basically just put all that code inside of hello here and the reason why I'm doing that is I want to unmount hello while the data is loading and then we try updating the state and that's going to cause a problem so I basically want to make this extra slow so the way I'm going to do that is I'm gonna say set timeout and we're gonna wait for some amount of time let's make it two seconds and then we are going to update the state all right so let's let's take a look at our example here so now if I increment it's just gonna take a second and then this should update and let's go to our hello we're kind of done with this example here I'm gonna comment out the use ref for that all right so let's go to our problem now so the problem that occurs is if I increment and then I toggle this off well also if this fails so let's refresh and try that again all right so we're gonna increment toggle this off so you'll notice what happens is it's going to try updating the state when the component is gone and we get this little warning and react so if you seen that warning before that's why you tried calling set state when the component is gone so we can use references to help us solve this problem so now what I can say is I can say Const is current is usually the name I'll give it use ref and we're gonna put the sign inside of our use fetch hook so by default I'm gonna say it is current sort of say is current is true and then I want to say use effect and I'm gonna say empty bracket here and I'm gonna return a cleanup function so this function is only going to be called called when the component is going to unmount and so we're gonna just say is current dot current is equal to false and so whenever this value is false we know the component is about the unmount so in our code right before we set set state we can say if is current current then we call set State so what's gonna happen is it's gonna load the value just fine when we increment here but now if I increment and I toggle it off what's gonna happen when the data loads is it's no longer going to call set state because the current value is false now you could also go about trying to cancel the fetch statement but this is another way you can know whether the value the current component has been unmounted yet is you can store that in a ref so does basically the basics of user F you can store whatever value you want in here and then you access it with dot current we didn't do an example with functions but again I could store our function here that I like we can console let's do is let's just make a function real quick and see what that looks like let's go to our app here and we're gonna say V the hello function and we're just gonna console.log hello and so there's some use cases where you want to put this stuff on a ref that comes up so we can say hello dock current and call it like that so now when I push focus it's gonna say hello and focus at the same time and again we could store objects whatever you like treat it as you would for example on a class component fields or instant variables that you would store on the class as opposed to stuff you'd store in the state but there you go that is an introduction to use ref so we're going to be taking a look at the use layout effect hook now this one has a niche use case which I only use on rare occasions now the key thing to know about this is this line right here from DOX it says the signature is identical to the use effect took but it fires synchronously after all Dom mutations and so this part is how it differs from use effect and in practice what that means is it's good for for example if you want to measure the box of something or measure the width of a Dom component after a render occurs or any kind of thing where we rely on getting information from the Dom and the use effect we want to try out usually out effect and practice a lot of times I'm usually taking this advice right here where it says we recommend starting with use effect first and only trying yet usually out effect that causes a problem so in practice that's usually what I do but I have found a pattern of where you use layout effect has been helpful for me so we're gonna be taking a look at a example of that so I'm going to measure the dimensions of this input field so I want to know how wide I know how tall and all that stuff and so what I'm gonna do is I'm gonna start by just saying use layout effect here and we're going to do just on first mount and then we are going to import it up here and here I'm going to say console dot log input ref we're already storing the ref up here so we have used ref input ref and we are passing out to this input here ref is equal to input ref and then here I'm gonna say get bounding client correct so this is a function that basically gives you the dimensions of this this component or this Dom node so if we come over here and this should be input ref dot current we can see in our log we can see the dimensions so here we can see the width and the height and we also see positioned on the page where it's at top left right bottom and X&Y coordinates so this can be helpful for doing different sorts of stuff and that's the basic gist of it whenever I want to get a value for example the measurements of a Dom node I will use usually effect instead of use effect so let's look at another example that is a little bit more practical so I'm going to go ahead and just console or comment this out and go over to the hello example over here so here for example I might want to know how wide or how tall this this div is right here because this data dynamically changes whenever I increment the number if we're gonna get a new fact it so this is going to be new text it's gonna be a new width so I mean we may want to know the width after each render so how can we do that and that's where usually out of fact can be used so we're gonna go over here to hello I'm gonna go ahead and just go to use fetch real quick and remove the timeout so this thing isn't super slow so I'm gonna just remove that and I'm going to keep everything else the same all right so here what I want to do is I'm going to first just put a div inside of this and reason why I'm doing that is if I come here and I open the inspector and look at this element you'll notice it spans the entire page so what I want to do is in this paired element say display flex and that way I can see just the width of it inside this small div here so we're gonna say display flex and then here I'm gonna store a reference to this div so I'm going to say Const div ref is equal to use ref we're gonna pass that in ref is equal to div ref and I'm going to get rid of this and I'm gonna say use later factor here and let's go ahead and put it up here now for the dependency I want to remeasure this every time there is some new data so I'm going to add data as a dependency here and let's start by just console logging it so I'm gonna say div ref current and dot get bounding client rect alright so we can see in the console log here it is has a width of 368 or 386 I mean and if we increment you can see the width has changed now to 285 so now we can measure it each time we change it the other thing is you may want to display something based on this so for example I may want to display the width so we could store this in a you state if we want to go back to Const and so here I can say div or let's call it wrecked and set rect is equal to you state and it's going to be an empty object to start off and so here I'm just gonna display this information I'm say rect or json dot stringify the rectangle and then in d usually out of fact we're gonna say set rect and let's not delete everything so right so every time we get a new piece of data we are going to get the size of this div and then we are going to update this state and we're going to display the new sized rectangle so here you can see the JSON for it and we can display this maybe a little bit more pretty if we use a pre tag and then we say null - to format it see if that gets a little better nice so now I can see the dimensions and I can increment and I can see we get some new values and new values for this that's pretty cool and we could turn this into its own custom hook if we want to so for example we could call this thing like use measure dot j s and here you could you could build this hook in a number of ways but let's say we just pass in the the ref to the used measure that we want to do it for and let's copy this and then what we return is the rectangle so here we're going to import all this stuff so import from react use state use ref and use layout effect I guess we could pass in the dependencies for the used layout effect as well say dependencies here and I guess react usually oh it was passed as a dependency list that is not an array literal oh I guess this doesn't know because it's of the type any even though we're in JavaScript interesting I guess it just says we can't statically verify so it's giving me a warning about it so I guess we can hit command and then period and we can just disable this for this line because we know that's gonna be okay or at least we are hoping it is so now instead of using a div ref here we can use whatever ref is passed in so this is one way that you could write this hook and so what do we get after we've written a hook like this so now I could just say rectangle is equal to use measure and then I pass in the div reference and then my dependency is the data and we can remove this and now I can just use my use measure like this so my use measure hook we have the reference here to the div and then here we have the dependency list of when we want it to remesh so let's see this in action and see if we got this correct increment and there we go we got it working nicely we could also if we wanted to do this move the reference inside of use measure here so move this inside of use measure so instead of taking this as a proper there we can say use breath and I guess I don't know what I want to call this my ref maybe and so we gettin past the rectangle as the first argument and the reference is the second argument to and we return this as an array so now in our use measure over here all we have to pass in is the dependency and we have the rectangle and then our div ref as the second value so now we have this used measure hook where I can put this wherever I want to so now I can use it in my app over here as well if I want to so I could say used measure and I want this to just do on initial mount we can pass in I guess I was going to pass in my input ref but here we can have another one put ref two and we have a rectangle and now we can pass it in here and now we're measuring the bounds of this input box here so now we've made like a nice little utility there and we are measuring it with the use layout effect but there you go that gives you kind of an idea of when you might want to use you use layout effect and how it works and we may have a custom hook here that you can use to measure the size of components and a few different ways you can build this hook depending on how you want it to work so we're gonna be taking a look at the used callback hook in this video it's good for when you want to prevent a function from being created on every single render now I'm going to explain what I mean by that and how this is helpful when we want to use the memo function and react now for those of you have been following along with the react hooks series I went ahead and I pared down the code because it was getting a little cluttered so here I have a single div and a Hello component that I'm rendering in hello we just have a div that says hello so we're just be starting from this place and where I start off by passing a function down to our hello component here so I'm going to create some state and we're gonna start with just a simple counter I'm gonna say count and set count and Rene's the you state hook so now normally if I wanted to say pass a function down to hello for example an increment function I might do it like this so I'm going to create a lambda here and I'm gonna say set count count plus one now you'll notice because I've created lambda here this is what I meant by creating a function on every single render every time app is rendered this is going to be recreated this function right here so and I also want to say for example display account maybe in this component so I'm gonna say count that and then in my hello component I want to use this increment function some way so I'm gonna say button and we're gonna hey increment every time they click the hello button we want to increment so we'll give that a save and then let's take a look at the code here so now if I say hello and I press that we're just incrementing so nothing special is happening so far but the key thing to note is that this function is being created on every single render so usually that's not a problem with what the current code we have not a problem whatsoever but what does cause a problem is when we want to use something like react memo so when I say react memo on this component I want this component to only a rerender when increment changes but the problem is increments changing all the time and so we can we can actually see this happening whenever I add some some logic here to print out whenever this component Ray renders which we can do 'but we saw in a previous video here we can say renders is equal to user F which starts at zero use ref and we can console.log renders and renders Plus+ so now we can see and this should be renders current and if we wanted to we could stick this in its own custom hook since we may want to use this several times so use count to renders so I'm going to say export can't use count renders and I'm gonna paste this code here and now we can put this we can keep the logic in this hook so now all I have to say is use count renders and now we're gonna get a console log every time this hook is rendered or every time that computed rendered so we can see a hello and now you can see that each time I increment count this is increasing right which we can actually improve this because this function is not changing at all right the function I want to do the same thing on every single time the only thing that's changing is this count variable here so how can we prevent this this is where use callback comes in so I can say use callback and it's probably good for me to explain this memo if you've never seen this before what memo does is basically it just compares the props and if the props have changed then it's going to re-render the component so by default react will always rerender the component if the parent is changed if the chair parents rendering this guy will render as well when we add memo it's going to check only rerender when the props are changed so we're gonna see the difference in that once we use the used callback so I'm going to say increment is equal to use callback and how you use callback works is we pass in a function and then it's dependencies in this little bracket array right here so here I'm going to pass in set count and now if I pass in the two dependencies they are count and set count and now I can pass this in here so how use callback works is whenever the count or set count changes this function will be recreated and put in this variable basically so now increments only changing when these two values are either those are changed so we haven't quite fixed it yet because if I come over here we can see it's still rendering every count and the reason for that is because we're depending on account right now so we can eliminate this dependency by using the updater function that is available to us only call set count here you can do like this so now what we have is if we come over here I increment the count here you'll notice the function is never changing and so this never gets re rendered and so this is where used callback shines is when we want to prevent functions from basically changing the value and a lot of times the reason why you want to prevent that from happening is when you're using react on memo because it's going to check the reference of something the other case where you may want to use use callback is in a case where you using for example like use effect and you have some logic and you need to pin on this increment function so you don't let this function to be changing all the time or else that use effect will keep firing off so those are like the two places where you'll tend to use these the most the other thing to note is we can add parameters to this if we want so for example I can pass in and and so that'll be the first parameter to increment so we can increment by an in amount so in my hello function over here I can go ahead and say increment by 5 for example and so that is going to be passed into our used callback function all right so now we increment by 5 the other thing you can do is you can actually return value from this or you can know you could return the I guess we could we can't really return the new count because we were doing an update or function here but it could return some value but usually when you're using use callback you're not really needing to return something so I don't think I've ever needed to return something but note that's available to you in cases where you need to so the last thing that I want to go over is a more practical example of where this comes up I found this comes up the most when I want to do a looping over an array of something so let's say we want to I'm just gonna create a favorite number a which is gonna be 721 and 37 is gonna be our favorite numbers for today so let's say I want to loop loop over these numbers here so I'm going to say favorite nums dot map and we're gonna say N and here we're gonna return and here I'm gonna create a square class component actually no it's not gonna be a classic one it's gonna be regular component and I'm treating copy our hello example all right so we're gonna render the square component here and let's say for example when I click on the square I want to increment it by the favorite number so I me do it like on click I want to increment by n right so this is a situation where again I'm creating a lambda usually not that big of a deal but if I wanted to for example memorize the square then things get messed up so it really just comes up when you want to memorize things or you want that function to not always you know where it it matters when this is getting changed on every single render when that matters that's when he kind of want to use use callback so we're gonna start we're gonna use our use count renders and let's just comment it out from our app over here or from hello because we don't want to get too much stuff on our output so n square over here I'm going to display the favorite number which is going to be N and we're also going to display in here and let's say we have an on click so we kind of showed this method with the hello example but we can see this again and we're gonna pass in down here alright so let's see what this just looks like we can also need a key so now if I increment by these numbers it's gonna increment the count you'll notice it's rendering each one of those every single time I click on a number for that many times now if we're doing a square here and we have on click that may be the standard way we want to do it but this is case is we're creating a function on every render and so it's causing it to render so the approach that I usually take in these situations is I'll pass the increment down and let's say we do increment and then we don't have the on click logic right here we put the on click logic inside of the square so here I have on click and so that we're going to say increment now and then we're gonna say increment and we can pass in in there so now if we come over here you'll notice it's not going to re-render every single time now because we're just not creating this function every render now so this is kind of approach that has come up a lot for me whenever I'm mapping over an array of items I'll usually pass down the function pass down the data and then inside of that function if I'm memorizing it I'll then have the logic for example the on click logic here or I call increment like this because we need this information there so there you go that gives you an introduction and to how use callback works and how you when you would want to use it so we're gonna be taking a look at the use memo hook in this video this is a hook that's great when you want to optimize computed values we're gonna start by looking at an example without it and then we're gonna add it in and see how it's actually helping and that's actually something I would recommend doing whenever you're using it for real and a project is start without using it and then if you see it like something as being slow or recomputed too many times then think about adding this hook in so we're gonna do is we're gonna start from here I have a single react component and I have a counter so I have a u state which is set to zero and then I have my counts that count and I'm displaying the count and I have a button where you click and increments the count so the task that we're going to do is we're going to start by fetching from this Kanye REST API so what this is is a list of quotes that Kanye has tweeted and we're going to fetch this JSON file here so I'm going to copy this a URL and I'm gonna display the word the longest word he uses in his tweet so we're gonna compute the largest word most number of characters a single word that he uses and one of those tweets is so we're going to start by fetching that information so I'm going to say Kant's data is equal to use fetch and when it passed this in that URL and it's not only me auto import I'm going to import from use fetch now use fetch is a hook that I created in a previous video if you are curious how this was created I recommend going and watch my use effect video in this react Oaks series basically what we do is we store the state which is null by default and we also tell you whether it's loading and then in a use effect hook here we fetch the data from that URL and then set the data in the state here and that state is what's returned so what we're gonna have is the data is gonna be null at first and then we're gonna get a ray of strings or yeah an array of strings what we get back from this rest API so what I want to do with that is I want to compute and we can create a functions out of here I want to also mention that so I'm going to say Kant's compute longest word I wanted to mention that I usually write arrow functions like this but we could also create a function inside of here like this that's totally a fine thing to do as well so we're gonna say compute longest word and we are going to say if we don't have any data it's going to return empty array otherwise we're gonna say let the longest word is equal to an empty string and we're gonna return the longest word and here we're gonna iterate through all the data so we're gonna say for each sentence and I'm actually going to say sentence dot split by space and then we're gonna do for each word so basically we're gonna enter eight through every sentence and then we're gonna split that sentence by space which will give us an array of words and then we know loop through each word and then for each word we're gonna say if we're dot length is greater than along this word dot length then longest word is equal to word and that's it and then we're gonna return longest word from this and then I'm going to just add a console.log at the top here I'm gonna add right here actually this is the more important one computing auguste word and then i'm going to display this down here so just get the longest they call it get no compute longest word so we're gonna give that a save and let's take a look at this data dot for each is not a function alright let's do a console dot log of what the value of data is and see where I ought wrong with this I was thinking it was gonna be an array of data you know what oh it's a text file I forgot we did that so in my use fetch I made I did X dot txt because the API we were dealing with was a txt file so I didn't do dot JSON we could change this to dot JSON here or in a file over here we could say oops say json stringify or sorry parse alright so you can see this is the longest word that he used in his tweets and so you can see we are computing the longest word here we did it once now you notice what is the problem with what we're doing so what we're doing here is we are computing the longest word and so this is what I would call is a computed value and this value we're computing is based on this this value right here I'm kind of just you know grabbing the value based on I'm not patent I'm not passing in the value through like a function here I could do that so it's probably a better thing to do so here gonna say array and array so that's the first thing what I was doing is I was just like directly accessing the data up there that can sometimes cause problems with closures and JavaScript so I usually like to pass in a parameter there so why don't we do that real quick and passing data here and basically what's gonna happen is if we start rear end during for example if I were to increment the count here we're gonna recompute the longest word every render so every time I increment discounters we are doing that for loop where we're looping over and finding what this longest word is so we're basically recomputing this value over and over again but the value doesn't really change because the data is not changing and so this is a situation where use memo can be useful but again a lot of times we don't even have to worry about adding it in like right here I don't see any performance concerns I don't see any lag in this situation I might even bother making it or optimizing this so that's something to note before you just jump in and use use memo everywhere it's something that I feel like you only need to use when you start feeling stuff being sluggish so pretend this was even more values and we're getting something that was sluggish what we could do here is we could say Const longest word is equal to use memo use memo and so how this hook works is the first one is a function that returns a value in our case we're gonna have a function here and we're going to pass in compute longest word passing in our data so basically this is the function that will return the computed value and then here we add our dependencies and so in our case only dependencies while our two dependencies actually are compute on this array and the data all right so we could add data and compute longest array or compute longest word well let's see what we did here so it function makes appendices of used memo hook to fix this definition and they use callback awesome so we're actually in yes Lent warning to put this in a use callback which was actually what I was about to talk about because right now compete longest word here is a function that's going to be recomputed on every render so use memo is going to do absolutely nothing right now because the value of this changes so I pass this in here so what longest word we'll store is the value that was computed here so whatever's returned from this function is gonna be stored in longest word so if we come over here we can see we're computing the word every single time and that's because this function is getting created every time and so this dependency is being recreated every time so there's a few things that we can do this could cause problems just removing it as a dependency cuz we use it inside of this so I usually recommend adding as a dependency but we could use the first step would be to just move this outside now that we are passing in the parameter there's really no reason for this particular function to be inside of our component here so that's really what I would recommend in this situation but we could also use use callback in a situation if we want to so just for demonstration purposes let me show you what the used callback could look like and actually let's just show that that works first so we'll give this a save so now if I increment this you'll notice we are not recomputing the longest word we only do that once and so that's really the purpose of use memo if you've used reselect with redux before it's gonna be a similar thing where you can now only have to compute things whenever the dependencies change here so whenever the dependencies change this value is recomputed and passed in here and so that's I use use memo in rare occasions when I need this but a lot of times I don't even need to worry about memorizing this sort of thing anyway let's look at the use callback real quick so I could pass this here and I could say use callback and so here we're gonna pass in our arrow function right here and to use callback so I over here I need to add a parenthesis and then I need to add the dependencies of this particular function which is an empty array because we're not using any dependencies inside of here all right so we can increment you can see it the same effect here it's not recomputing I think also if you're using use callback somewhere and you don't have any dependencies that's probably a sign that you can actually just take the function and put it outside so in this case I wouldn't recommend using you just undo all the way up to here I wouldn't use use callback because there's no purpose if you can I would you make functions like this where they are pure they don't use any outside things and you just pass them in as parameters and you can stick them outside like this that's what I would recommend for situations like this so there you go that is what use memo does and when it is useful so we're gonna be taking a look at the use reducer hook now this hook is for storing state and is an alternative to the used state hook so we're gonna start off with a simple example and then make a more complex one to demonstrate how to use it so start off we're going to import a used reducer from react and we are going to call it so use reducer and our component right here and how I use reducer works is you pass it to parameters and we can see that if we hover over we can see the signature you can pass it the reducer which is a function which is gonna be very similar if your some are really exactly the same as what you would do in redux if you're familiar with that if you're not no worries we're gonna go over how that works and then also the initial state or you can pass in a a function that returns the initial State as well so the reducer is a function so I'm going to say Const or we could say function reducer instead if we didn't want to use an arrow function you'll notice I am creating this function outside of the component here that's on purpose this is a function that is pure and we want to stick outside of our component we don't want to create it inside all right so I have my user reducer here in the pass and reducer and I'm going to put my initial state just start off we're going to do something simple when you do a counter so my initial state's going to be zero and again if we wanted to initialize this we could with a function so same thing and again same as you state you'd want to use a function if the initial state was took some time to compute or something like that all right so in a reducer how it works is it takes two parameters the current state and an action so the state is going to be whatever the current value is in the state and the action is basically a function that gets called and the value is going to be stored here so what it looks like is here we're gonna return a state value whatever the value is in this case it's gonna be count and then a function called dispatch so here we're going to say div counts is equal to account we can see the value of count and then I want to create a button to increment and we're also going to create a button to decrement so now what do I put here I'm gonna call dispatch and I need to call dispatch with some parameters to get this to work so I want to say decrement so basically whatever I pass to dispatch right here it's going to be this parameter and the reducer so if I were to dispatch one action would have the value of one i dispatched to here of the value of two now there is a basically best practice or general way you see people using dispatch and reducers like this in redux and so we're going to follow that similar pattern so usually how it works is you would create an object that you pass in or you pass in a type which is usual string so here is where I'm gonna pass a string and you can make this all caps if you want or I sometimes just do all lowercase and put it there you can also this is something where you can store in a variable we could say increment is equal to increment it really comes down to whatever you want to do there we're gonna just keep it simple and start with here but you can follow some of the redux best practices if you like with this alright so we have this object that we're passing in we said the type increment and that's really all we need to do and then here I'm gonna say type decrement so now in my reducer basically what I do is I read what the action is and I change the state accordingly now you can do whatever syntax you want inside of this reducer but the most common one you'll see is a switch statement where you say action dot type and so here we're gonna have different cases so for example when we have an increment action passed in what should we do well we should say return state plus 1 and when we get a decrement state or action I mean we're going to return state minus 1 and then here we're gonna say default return state and default is whenever the action is not an increment or decrement the default thing we should do is just return the state so let let's see what happens when we do this so now we're gonna see is I increment the state in decrement the state the state changes and so we're basically are listening for these actions that are being dispatched so this is what you'd call an action and the different types we react to them in different ways all right so that is the basics of use reducer so we basically create a function that changes the state a key point with this is you do not want to mutate the state inside of this so I don't want to do state plus plus I want to create a new version of the state that is state plus 1 so that's very important so now that example what we're going to do is we're going to build a small little to-do list to show you some of the different ways that you would use the reducer for this so now my reducer I'm going to make it an object and it's gonna have some to dues in it it's gonna have an empty array by default and that's what we're gonna start with so now here my state is going to be an object and state dot two dues will have this value in it you can also de structure this if I want to like that so what I'm going to start with is an input field and this input field is going to be basically we're gonna wrap it in a form this is how we're gonna add two dues to our list now a good thing to note about this is we can mix hooks all we want so even though I have use reducer here if I was making this I would probably just use you state to store the state of a input field so I'm gonna say you state and I'm gonna say text set text so I'm going to pass the value of the input text there and then the on change is going to be set text a target value and now when this form is submitted on submit what I'm going to do is I'm going to add a new to-do list or new to-do item on here so I'm gonna say e dot prevent default value so if you don't do this the form will refresh the page so we're going to do that and so whenever someone hits the enter key this is gonna add a to-do to this so we want to say dispatch and our action is going to be add to do and the other thing you can note about actions is you can pass an other data in there that you need so for example I want to pass in the text so here I'm going to say text and that's from the U state and so now I need to create my reducer to handle this new action that I added add to do here and I'm gonna go ahead and say pre json stringify these to do that way we can see what this looks like we can see our array so as we add to Do's and hit enter we should see them displayed here once we add the dispatch for it I'm also going to set text and clear out the text whenever I dispatch here so here inside of this I'm going to say add to do and I'm gonna get rid of decrement so here I'm gonna create a new object I'm gonna say dot dot dot state or in this case since we only have one item I could just say to dues and I'm gonna say dot the thoughts state dot to dues so I'm gonna keep all the existing two dues and I'm gonna add one on so I'm going to say text is equal to action dot text the other thing to note is usually the you'll usually call this payload and the payload you may put different values in so we could call the payload text or we could just call it text here she's good to note that some people will name it that way but I'm just gonna call mine text there some of say text : action nots text one thing you'll notice if you're familiar with Redux is I didn't do it this way I see I'm a little bit looser when I'm using use reducer and a single component that I am if I'm using Redux and I need to be I guess following the same convention all over my entire application so it doesn't get messy I tend to be a little bit looser when I'm just using use reducer but maybe it's better to be stricter not just one note I've noticed that I've been doing and so here I'm going to say completed is gonna be false all right so let's see this in action now I'm gonna say 1 enter 2 and we can see our state is growing now as I add items so cool so now I want to display these items not like this but just in a list so I'm going to say to dues map and then for each T I'm going to display a div and that's going to have the value so tea text and the key I'm going to say T dot text as well so don't put duplicate text or this gonna get mechs messed up since we're using that for the key so let's see this now so I gonna say one two three and excellent those are showing up let's go ahead and now add another action so when I click on the to do I wanna cross it out so on click I want to dispatch a new action that says toggle to do and I want to do that a certain index and our map function the second parameter is the index so index we can pass that right down so now am i toggle to do up here you can copy this case say a toggle to do we're going to keep actually we're just going to get we're gonna get rid this we're in a totally different way to get this to work so whenever I need to update the value basically we need to go through this list and we need to at a certain position at that index set completed to false or set to true basically inverse it so in situations where you need to update a certain item in a list the way I like to do it is say state dot two dues and I like to map over it so the map is going to have a to do value and then the index and then what I do is if the index is equal to action dot index then I do a ternary and I know this particular item when I'm mapping over is the one I need to change otherwise I just return the current to do so here I'm going to say dot about to do so I'm going to keep all those existing values in the to do in this case just the text and then I'm gonna say completed is equal to t dot completed and then I'm gonna inverse that value so what this chunk of code does here is it's going to iterate through the list of two dues that we have and it's going to flip completed so if the value is true it's going to go to false and we do it at a certain index all right so let's see that in action we're not making a visual difference yet so let's do that so we can actually see the change happening so here I can say text-decoration and we can say strike the strike through this may not be the right this may not be right we'll double check in a second we're gonna say T dot completed sequel that other whites it's an empty string all right so let's say one click yeah it's not right so I'm gonna right click inspect here I'm gonna click on this item and I'm gonna say text-decoration strike oh is it not that maybe it's a different one I thought it was me text transform nope that's one of these properties text I thought was decoration oh that's called line through all right so will it rename that so this is also by the way you get all the completion here and if you open the inspector elements and then go to styles that's what I was doing here to try to figure that out so one and I click this you can see it toggles on and off as I click it now so pretty cool and so that's the gist of use reducer you'll have an initial state of some sort you'll pass a function that's a reducer and that reducer is going to handle different actions throughout your or different actions through your application and then you're going to call dispatch to trigger those actions you're gonna pass any data you may have in your gonna pass a type and then your reducer is going to handle updating the state so all your logic of updating the state goes in here so why do people like using this overuse state what is nice about it well our state here is relatively simple but when you get into more complex state it's nice to be able to change multiple things in the state based on actions so what is an example of that well let's say we also want to store the number of two dews we have so maybe that do count so we'll set it to zero so whenever we added to do we not only want to add something to the to do now we also want to increment add to do or sorry to do count so now I say State DOT to do count plus one so now you can see and we should also keep to do count is equal to State DOT to do count whenever we toggle it to do here so now you can see and let's actually verify if this works and then I'll talk more about that so number of to Do's and now we can display that we can D structure it from up here to do count and let me just make sure I didn't say - duze yep good all right so I can say 1 2 3 you can see it's now counting there so as you can see as we get more complex state a single-action might map to multiple things in the state changing and so it's very easy to put that logic in a reducer like this so for those of you that are wondering when should you use you state or use reducer because that's really the question that's gonna come up next because you can use them both for storing state I have a video that goes more in depth over this question I'll link it below if you want to view it but the short answer is whenever your state gets more complex use use reducer if something you have is very simple you can use you state and I think that's the distinction I usually use the other thing to note is if you're familiar with Redux you'll notice is very similar so when should you be using use reducer over use Redux again I have another video I believe going over that I'm so I'll link that below as well but the short answer for that one is if you're using the state and a single component for example in this app I have it all inside of here like using use reducer if you want to use this state in multiple components and they're spread out in that state it relies on each other that's when I like using Redux or another state management library rather than putting use reducer and maybe sticking context with it and trying to spread stuff out that way or passing down props I much prefer Redux or state management libraries in that scenario so that's that one last thing that I wanted to mention with this is you'll notice the object with this can get quite ugly especially if this is a very nested object having to create a something immutable and that we don't want to change the value of the state it's kind of annoying sometimes so I highly recommend looking at this library called use Emmer if this is a problem you have because basically what it allows you to do is you can mutate the state and basically underneath the hood it'll handle making an immutable change for you and so this can be very helpful when dealing with large states and reducers and it works for you state as well so I highly recommend looking at this if you get some complex use reduce your logic but there you go that is an introduction to use reducer so we're gonna be taking a look at the user context hook now one of the most frequently asked questions I get about this is how you can store a user in the context and share it throughout your application so in this video we're going to be using the use context hook to do just that so what I have set up here is a small application using react router what it looks like is I have a single page or two pages I have an about page and a home page and you can toggle back and forth between them and so what I want to do is I want to be able to get the user or who the current user is on both the home page and the about page so that's what we're gonna do in this video now the code for this is right here this is my router so I have a navigation bar that's being displayed on each page and then I have a react router Dom router and a route that's displaying an index and an about page now my index looks like this I'm a about page looks like this so very basic components we just have an h2 that is being displayed so let's go ahead and get started with this so the first thing that I want to do is create a context to share between my components so what I'm going to do is I'm going to create a new file and I'm going to call it the user context is and I'm an import from react and what I'm going to import is create context and I'm gonna say export Const user context is equal to create context and here I can pass them when I want the initial value to be in this case I'm gonna have the initial value be null so now this user context I'm going to import in my app over here so I'm going to say and I'm going to wrap the components in a provider now this is going to encompass all my components that I want to be able to grab the state from so for example if I want to get in my index in my about page both of those components if I want to get the user context value then in my provider I need to wrap these two so what I'm going to do is I'm going to say user context dot provider and this is a component which I wrap around whatever components I want to supply be able to get the context for all right so I have my provider here and then I can pass some kind of value so the value I'm gonna pass it's just hello from context so now what I can do is any of the children components inside of this provider I can get the value so how do I do that well let's start with the index page over here so I can say Const message it's equal to use context so we're gonna use the use context hook and now we pass in the context that we want to get the value for in this case is this user context that we created I'm gonna copy that over and I'm gonna import that and so now I can display this message so on a display a div here and I can display my message so now if I go to the home page and give this a refresh I'll die crash things nope I just forgot to restart it so we'll restart this back up so now we go to our home page we're gonna see our h2 element home and then we're also going to see our div element with the message which is going to be the value of the value in the context and that's this value right here that we're passing to the provider all right so now we can see hello from context now on our about page still blank so we can grab the same context value over here and we can display it the same way so I'm gonna copy this paste it here and this is the about page and let's import this stuff it's not gonna let me auto comport that one but let me do it there and now we can get this on both pages so the advantage of using context is we can get the value of something no matter where the position this is in the component tree so this could be a deep child and we can access the user context by saying the use context hook now we can make this more advanced by changing the value that's being stored in the provider and then everyone is going to get the update so what do I mean by that well so I'm gonna say Const you stayed up here and this is just gonna store the state of the value so in this case you can say hello from context and import use state so this can be value and we have set value so now what I can do is in my provider here I can pass in an object which is value and set value and now in my components over here I'm gonna move this over to the side actually I think we're done with use context and just going to close it so now my components I can get a value and a set value so let's play value their copy this and do it in our about page - and now over here I can say set value when I want to so button change value and we're gonna on click and set the value to hey so now we'll refresh this oh we're guess we're on the about page I was like why aren't we seeing a difference all right so now when I click change value here you'll notice the value here changes and now when I go to my about page it also changes here so basically whenever the context value is changing or that provider value is changing we're gonna get the changes through use context and we can access whatever we pass in as a value here in this case the value and set value now if we want to you'll notice we're creating a object every single time to pass into value one thing we could do here as we learned is we can use the used memo hook to create what the value is so here I'm going to say provider value is equal to use memo and here we're going to return an object the value and set value and I want to do this whenever value and set value changes so provider value in this case this is not going to make a huge difference but if your component is making a lot of changes the value of the object is always going to change so this prevents this prevents this provider value from changing unless the value or set value changes okay so let's take this to the next level now so now you've seen how we can pass some state and threw out basically multiple components using use context and how we can pass also an object and get functions that we can actually call and we can update the state and we can update that state across multiple components so the next step is to actually start storing a user and so basically we're going to do the same thing with a user so here we're going to start with a all value we do not have a user and then we may have for example a logon so here I mean I say login and by the way I can change this to be user and set user I think that's better so set user and user and I can just rename this to value if I want to also good to note you can push f2 and vyas code and then I'll let you rename something and it will change it all over the place so now we can say user and set user in our context so now what I'm going to do is I'm going to display the user by saying json.stringify user and we're gonna do pretty tags here and I'm gonna say null too and it's going to be set user and I'm going to copy this to my about page over here so user set user in case we want to set the user in the about page we probably are not going to but in case you want to do you have access to that so now in my index we want to login the user so how might we vlog in a user so I'm going to make this a a synchronous function here and now when I click on this button I'm going to get the current user by logging them in so it's login and I'm going to import this now this is a function that I just created here login over here it's not letting me auto import it which is making me sad now it is I just had to open it up so for the sake of this I'm just mocking this login function but it returns an object which is the current user now of course in your application I want to go ahead and make a request to the server for example and get the user if they logged in correctly but you get the idea so we login we get the current user and we can store it in our context like this alright so now let's look at our application over here we can see the user is not there to start off with and I guess is the about I keep coming to the bow page and wondering where my button is so now if I login we can see the user shows up and so now I can do fun stuff like I can conditionally render buttons so I can say if we have a user display a logout button if we do not have a user display a login button so I just added a ternary here so if we have a user logout otherwise this so then our on click here you know I can call logout to my server if I need to and I can say set user is equal to null all right so now I can see I can login we have a user in our context and now I can log out and it's null and now the cool thing about this is this is affecting all the different pages that need the user so am I about over here is null if I log in you see the about has the current user and then we can come back again and we can logout and you get the gist so the point is that is how one way you can go about storing the user and passing it throughout all your components get that value using context the gist of it is at a top level you store and some state the current user and then you allow other people to see that user by creating a context and passing the value down and then those components subscribe using use context and now whenever that user changes we get a new value in our state here so there you go that is how you can use use context hook and react you
Info
Channel: Ben Awad
Views: 158,962
Rating: 4.9563165 out of 5
Keywords: react, react hooks, React Hooks Course, useState, useEffect, useRef, useLayoutEffect, useCallback, useMemo, useReducer, and useContext
Id: f687hBjwFcM
Channel Id: undefined
Length: 105min 6sec (6306 seconds)
Published: Tue Jul 02 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.