Learn React Hooks: useReducer - Simply Explained!

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
what's up guys Terrace cousin here welcome back to another react tutorial this one has been heavily requested it's a tutorial on use reducer in react make sure to watch and watch until the end of the video because if you do I promise you you're not gonna have to watch another video on use reducer ever again also before we start I do want to mention that I created a Discord for react developers it's the first link in the description down below it's essentially a community of developers just like you trying to learn react where you also have access to me personally to help you on your journey I answer questions I review code I take in video requests and I'm generally available to you to help you in whatever you need so if that is of interest to you it's the first link in the description I would love to see you on there and with that being said let's now jump on my computer screen and finally talk about use reducer cool so we're now on my computer and as always I have a very simple application so simple that it's actually three lines of code which I'm going to use to teach you about use reducer now use reducer what is it and what you use it for the simplest way that you can think about use reducer is really compare it to you state it is very similar both of these are hooks that you use to manage and update state in your react application the only difference with use reducer versus use state is that use reducer functions a little bit differently use reducer follows the Redux pattern of doing things if you've never used Redux that's fine don't worry you don't need to use this for this video but it's essentially having a state object with a lot of properties of values for your state and then having a reducer function which takes in that state object along with an action that you can Define in your code and based off of the action will do something to that state we'll make a copy of the state make some changes and then return to the copy of the state to then overwrite and make a new state this is very important and this is what we call immutability we're never actually mutating the data directly we're always going to work with copies of the state making our changes to those copies and then returning that state so that it gets over overwritten in the actual state with userducer this is very similar to how you would do things in your state and as you're going to see everything that we do here with use reducer can also be done with your state and the whole point of this video is that you understand how use reducer works so that you know when to use which cool so with that being said let's start working with use reducer the first thing I'm going to do is I'm going to import use reducer from react so import reducer from react and then I'm going to create our state object so the syntax for it is like this constate dispatch and then use reducer as you can see this is extremely similar to how you would do this if you were to use you state it functions the same way you get back the actual State object and then a function that you can use to manipulate that state the only difference between user reducer and use state is the fact that use reducer takes in some arguments here you can see that it's expected two to three arguments but got zero two of these arguments are required one of these is optional and in this video we're only going to talk about the two that are required because that is enough for you to completely understand how use reducer works if you're curious and you want to learn about the third argument of use reducer which is optional you can go ahead and open up the react docs and find all of the information that you want from it there now the first argument that you give to use reducer is the reducer function this as I've said is a function that will take in the state take in an action that you can Define in your code and then it will make a copy of that state and then based off of the action it'll do certain things to the state to make some changes and then return to the copy that is then going to go into the state variable through this use reducer hook the second argument is the initial value of the state variable this is very similar to how you can define an initial value to you state when you use that with the only difference that in this case it is actually required it's not optional you have to give State an initial value before you do anything to it or else you're going to get an error like we have here cool now before we create our reducer function and our initial State I want to First create the types for our state and for our actions because those will then get used and automatically inferred throughout our code when we use use reducer so the first thing that I want to do is I want to create the type of our state so I'm going to do interface State and then this is going to hold our state now in this application as we've always done on this channel we're going to make a counter application right that is the simplest way to illustrate this so our counter is going to have a property called count which is going to be of type number so count number and then what I also want to add is I want to add an additional property that we're going to call error and that is going to be of either type string or null and this we're going to work with a little bit later I'm going to show you the benefits of using use reducer in this case over using new state and now we need to create the type for our action the action is going to be the thing that signals our state to change in a certain way and we're going to use this action to determine what should we do to our state so I'm going to do interface action and this one is going to be because we're working with the counter example we're going to have two types two cases that we need to consider when mutating the state we're going to have to consider the case where we increment the count and the case where we decrement the count so the type here is going to be a string literal of increment and of decrement right so our action is only ever going to be allowed to have either increment or decrement as its type and again we're going to use this type in our reducer function to figure out what we want to do for our state so now let's create our reducer function so we'll do function reducer and this will take two arguments the first one is going to be state which is going to be of type state right that's why we typed it and then the second argument is going to be the action so action and that is going to be of type action now this function as I've said it's going to take in this state it's going to take in the action it's going to make a copy of the state and then depending on the type of the action it's going to make some changes to that copy of the state and then it's going to return the state with the changes applied so what I'm going to do is because we know that type here is always going to be present on action I'm going to destroy structure type from action so that we can use it directly as its own variable so I'll do cons type equals action and then what I want to do is I want to create a switch statement based on the type and then do certain things depending on which type it is so I'll do switch type and then we're going to do for now I'm not going to add the code for the increment and decrement cases I'm just going to do default and then return State because I don't want typescript to complain I want to build out the rest of the application first and then we're going to come in and actually add the code for each individual case and this for now will just return the default state which is the same state that it received and so it's not going to be a different object and react will not re-render the component cool now we can put our reducer function in our reducer so reducer and then we can Define our initial state which is going to be count 0 and then error we want it to be null cool so with this we now got rid of all of the errors that we had and we've successfully completed the setup of our use reducer now what I want to do is I have some code here that I've pasted that I've copied from before that I'm going to paste here this will just set up some buttons and some things for our app it's really simple don't worry too much about it we have essentially here a line that shows us the count from the state right state to dot count then we have another line here which checks the error in the state and if there's an error you're going to render out this error and then we have two buttons one for increment and one for decrement which both called the dispatch function the dispatch function is of course coming here from this use reducer hook and what it does is it dispatches with an action and here we gave it the type type increment and type decrement and by the way this is typesafe right so if I put an extra T here typescript is going to complain that it's of the wrong type that is why we have typed here everything here so we get automatic type inference into our application when this dispatch is fired it's going to send the action to this reducer function which will also get the state from the use reducer hook get the action and then based off of the action this code here which we haven't written yet is going to do certain things to the state based on what type the action is so now if I go here to the app and I press increment I press decrement nothing happens of course that is because we haven't added any code here for any of these individual cases so let's fix that let's start with increment we're going to do here case increment and then we're going to open the curly brackets and then we're going to think what do we want to return well we said that we always need to make a copy of the state so let's start with that return State this will make a copy of the state and if I can spell return properly and then what we want to do is we want to overwrite and actually increment the count so what we can do is we can do count right this is a property of our state and then we can do state DOT count because we have access to the state as of this and we can do plus one so this will return a copy of the state because we're using this spread operator here and then it's going to overwrite the value of that copy the count value to the state DOT count plus one and then we're going to do the same thing for decrement just minus one so we're going to copy this actually we're going to do decrement and then here instead of plus one we're just going to do -1 right if I now go into the application and I press increment it works as expected I press decrement it works as exit we have now a fully functioning counter application using use reducer now again you're going to realize that we could have done this with you state it would have been actually easier and less code to do this with you state that is fine that is normal like I said both of these hooks do the same thing they allow you to do the same thing but the way that you get there is slightly different but now let me show you something that you can do much more easy with use reducer than you ever could with your state we have here this error property that we haven't used anywhere in our code let's now change the rules of our application it's no longer just a simple counter we're going to now add some restrictions the count can only be between 0 and 5. if it's above 5 we want to throw an error if it's below zero we also want to throw an error so how will we do that in this code right here well what I'm thinking of doing is I'm thinking of creating a new variable called new count so const new count and that is going to be equal to exactly this what we had before so I'm just going to copy this and paste it here and then I'm going to create a new variable called has error once test error and that is going to be equal to new count greater than 5 right because we said that if the count is greater than 5 we want to throw an error and here now instead of just updating the count every single time I'm first going to make a check for has error and depending on that I'm going to update the count or not so I'm going to do has error and then question mark because we're making a check and then if we have an error I don't want to update account I want to give the count that was there before so state DOT count otherwise I want to do new count then I'm going to put a comma make a new line and then handle the error because we also want to set this error in our state so I'll do error and then here we're also going to make a check for has error so has error question mark If we have an error I want to put an error in our state which as you can see can be of either type string or null so I'm just going to put a simple string that says maximum reached if not I want to put null so now this code what it does is it will not I'll just update the account directly it'll first check if the new count is greater than 5 and so if it is this has error is going to be true and then it's only going to update the count to the new count if has error is false and if has error is true it's going to set the error here at maximum reached and then what we can do is we can come here we can copy all of this come here in our decrement case paste all of that and just make the changes where here it's -1 and then here it's lesser than zero and instead of Maximum it's going to be minimum now remember we do have this line here on 948 that says if there's an error we're going to show the error on the screen so if I go here to our application and I click increment this should be fine one is fine two is fine 3 4 5 is also fine but now if I try to increment again our code should not increment to anything else other than 5 it should stay five and the error should show up so I press increment and we have error showing up and we still have a count of five then if I decrement the error goes away the count decrements everything is fine the decrements everything is fine why did this open everything is fine I go to zero it's fine and then I try to go below zero I get minimum reached and the count is still at zero now see this is the benefit of using use reducer over using you state you can have all of your logic for how the state should behave based off of actions in one place and at the same time you can update multiple pieces of State at once if we had done this with you state probably would have had a state value for count and then a state value for error and then we would have had to create our functions to update that and add all of that logic here this way it's more concise it's easier to read easier to understand and a lot easier to work with now I really want to stress how important it is to understand that there's no right or wrong way there's no way that is better or worse than the other it really always depends on the context and which way is the most appropriate for the thing that you're trying to do both use reducer and use State allow you to do the same thing the difference is how you get there and how your code looks like in the end so really the go goal for this video was to teach you about use reducer and how it works so that you can make an educated decision when you want to use this overview state or vice versa and I really think it's super important that you spend all the time that you need to really understand how use reducer works and how it's different than you state cool so there you go now you know how to use use reducer I really hope that you've enjoyed this video and you found value from it if you did please leave a subscribe leave a like it really does help me out a lot and it shows you that you enjoy my content and that you want more videos which again I will make plenty of more videos also remember the first link in the description is the Discord Channel I'm really trying to build the biggest and the greatest react developer Community there ever was and I would love for you to be a part of it and yeah my name is bindaris cousin this is causing Solutions it's been an absolute pleasure and I will see you all in the next tutorial ciao
Info
Channel: Cosden Solutions
Views: 48,385
Rating: undefined out of 5
Keywords: react tutorial, react crash course, react developer, learn react, react hook, react hooks, react hooks tutorial, programming tutorial, react hooks explained, computer science, tutorial for beginners, react component, learn programming, web development, frontend development, coding for beginners, simple code, easy programming, useReducer hook, useReducer tutorial
Id: rgp_iCVS8ys
Channel Id: undefined
Length: 13min 48sec (828 seconds)
Published: Thu Jun 22 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.