Learn useReducer In 20 Minutes

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello everyone in this video I'm going to talk about the use reducer hook which is one of the more complex react Oaks but I'm gonna break it down step by step so you know how to implement this hook in any of your react projects also if you want to take your react skills to the next level and learn everything you need to about react make sure to check out my full react course which I'm gonna link down in the description below let's get started now welcome back to web dev simplified my name is Kyle and my job is to simplify the web for you so you can start building your dream project sooner so if that sounds interesting make sure you subscribe to the channel for more videos just like this one now to get started I have a really simple counter application on the left and you can just see we have a simple state that defaults to zero and increment and decrement button down here which we have minus and plus and as we click the plus button it goes up and the minus button it goes down this is a very simple application and a great example of how you state works but you state is not the only way to manage state and react there's something called the used reducer which also allows you to manage state and re-render a component whenever that state changes and the idea behind use reducer is it gives you a more concrete way to handle complex state so it gives you set actions that you can perform on your state and it's going to convert your current state to a new version of the state based on the action that you send it if you're familiar with redux the use reducer hook has a very similar pattern to redux I just feel it takes away a lot of the boilerplate that's associated with redux so to get started we're gonna convert this counter application to use reducer because this is a simple example that will really demonstrate how they use reducer hook works so let's just import that use reducer hook and to use a user reducer if we come down here it's going to return to us an array and then we can just say use reducer and this reducer function is going to take two different parameters to start we're going to have a reducer which is a function that we perform on our state to get new state and it's also going to have an initial value so we're gonna pass it a function which we'll call reducer we can define that up here reducer just like that and then we're going to pass it our initial state which in our case we're just going to use an object I'm going to set the count here to be equal to zero just like that and now this is essentially the same as setting up our state down here with a default value of zero we could pass in zero here instead of an object but generally when you work with reducer and use reducer you're going to use objects instead of actual values just because generally your state is more complex than just a single value so we're going to use an object here just because that's most likely what you're going to run into now this return value is going to be two portions the first portion is going to be the state so in our case this object right here so we're going to call this state just like that if we had set this to a single value for example just zero then this would be our count but in our case we have it as an object so we're going to use state and now the second thing this returns is a function called dispatch and as a dispatch function is essentially what we call in order to update our state essentially it's going to call this reducer up here for us given certain parameters and this reducer is going to take two different things it's going to take the current state so essentially where our application is currently at and it's also going to take an action this action is what we pass into this dispatch function so whenever we call dispatch what's going to happen is whatever we call dispatch with is going to get set to this action variable here and then our current state is going to be in this state variable and a reducer is just going to return our new updated state so an example that we can take a look at would just be if we just did here return count of a state dot count plus 1 now every time we call dispatch it's going to increment our count by 1 and let's get rid of all of this code down here and instead of our increment which is called dispatch we're just not even gonna pass anything or just gonna call dispatch and then down here we can put our state count and for now decrement is not going to do anything so if we save and we click plus you can see we are incrementing our count by 1 each time because every time we call Road right here which is our dispatch function essentially we're taking our current count and adding one to it now obviously this is not a very useful example because this is a very simple use case and we're only handle in one state we're only handling our increment state what happens if we also want to decrement instead of just increment well in that case what you do is you generally are going to pass a type into your dispatch so here at a pass an object with a type and this would say for example increment just like this increment and then inside of your reducer you're generally going to have a switch statement or some form of if statement and what you're going to just go over our action type and we want to check all of our different types so our first case is going to be for increment and if we are incrementing then we want to return our state essentially added to itself plus one just like this our next case is going to be for decrement so we can say decrement whoops affected spelled properly there we go and in this case all we want to do is return our state minus one instead of plus one and then generally it's a good idea to have a default case either here you can throw some form of error if you want or generally I just like to return our current state essentially this is not a valid action if we're not incrementing or decrementing we just do nothing with the state so we're returning the state we already have and that right there is our entire reducer function taken care of we have our multiple different types so essentially these types are like the actions that you can do on your actual state so we're saying the only two things that we can do to our state is incremented and decremented and then whatever we want to do that we just called dispatch and pass in that type in our case increment and for decrement we would just do a type of decrement here now what's going to happen is if we save we can click plus and increment and minus and that's going to decrement our account and we have no other way to modify this state other than through the actions that we have predefined this is a great way to make sure your state only changes in ways that you expect it to and not in some weird unexpected way another thing that you'll notice is that we have these hard-coded strings for increment and decrement scattered throughout our code this is generally something I really don't like so what I do a lot of times is I create a constant variable we're just going to call this actions we're going to put it in all capitals because this is a global non invariable and we're going to set it to an object which is going to contain our different actions so we're going to have increment is going to be set to the text increment we're going to do the same thing for decrement we're going to set it to the text decrement and then instead of using our hard-coded strings here we could just say actions dot increment and down here we could say actions dot decrement and then again same thing down here instead of passing the string we're gonna pass in our actual string values for our object so we can have hard-coded values and that way we have autocomplete we don't have to worry about misspelling a string because if we misspelled something here it's going to give us a warning or an error especially if we're using something like typescript to type-check all of this so this is just a much safer way in my opinion to handle this incrementing decrementing and different action types instead of having hard-coded strings everywhere also if I want to change our string I could just change it here and it'll persist throughout our entire application without breaking anything which is really important now as I mentioned at the beginning of the video use producer is really not that useful for a small state like this counter it's a lot of extra code to handle this counter and it's really more important when you're working with more complex state or a lot of nested components that you have to worry about passing props down into so let's take a look at an example of a really simple to do application to show you how this can actually be used instead of a more complex use case and really show you the power of use reducer so let's essentially clear out a lot of this we're going to take our reducer here just remove everything inside of it get rid of all these actions because we're going to have to do related actions and then inside of our state here for our app we're just going to have to do and instead of doing an object here we're just going to use a simple array because we're only going to have one thing in our state so we don't actually need that object get rid of these functions here just like that and then down here we can actually set up the code for our form which is going to be for our input so let's have a simple form with a simple input type of text value we're just going to set equal to name and all change what we're gonna do is we're just gonna set a variable to be that name so we can say set name is going to be equal to here whoops y target dot value and close off that input and we want to make sure we actually bring in that state so we're gonna have name set name that's gonna be used state with an empty string and we're gonna import use state up here there we go we should have an input over here and we can change it and that's going to update our name variable right here the next thing I want to handle is what happens when we submit our new to do so we could just say handle submit let's just create a function up here for that and ole submit and inside this handle submit function all we want to do is add a new to do so we could say dispatch and we're going to have a type here which is going to be for our new to do so let's create that action up here new to do what you just call it add to do we'll say add to do so now we can say actions dot whoops dot add to do just like that and then we can set our name back to an empty string which is going to clear out our name so if we just save type something hit enter you can see it clears out our name but it's refreshing our page so let's just make sure here we do a dot prevent default that's going to prevent our page from refreshing now if we type hit enter you can see everything's working perfectly fine it's clearing out our input but obviously our reducer is not doing anything with this ad to do so up in our reducer let's get that switch statement back we want to switch on action type and the first thing I want to check is going to be that actions dot add to do and what are we gonna do when we add it to do well we need to take our current state which is all of our two dues and we need to put that into an array so we're going to say to dues is this is actually all of our two days instead of state this is all of our current to dues and then what we want to do is we want to add on a new to do so we'll just say new to do and inside of here we need to pass some form of name variable to this new to do and then we can create a function called new to do which takes in the name we can just return our new to do so our ID is going to be date dot now I'm going to set our name equal to our name and complete is going to be false because if we create a new to do obviously it's not complete yet but you'll notice immediately one problem where are we getting this name from we have it here where we set our name to this name variable we don't have access to that inside this reducer function so something that you commonly are going to do with reducers is you pass in the type which is going to be the thing that you want to do and then you're gonna pass in what's called a payload this can be named anything I'm just showing you the common conventions this payload is an object which essentially contains all of the variable values we need to actually perform that action so in our case we need to pass in a name so we're gonna pass in the name which is equal to our name here now we have our action that payload dot name which is going to be equal to the name that we have set to this named variable here which is inside of our input and then it's going to add a to-do to our list and if we just come down here in console dot log r2 dues and if I inspect the page bring this over so we can see the console and I type something in and hit enter you can see it adds a new to do for us and it contains the name of whatever I typed in we have our ID and complete is equal to false so I want to just reiterate what happened here because this is really the magic of the use reducer function is this type variable is getting passed in add to our dispatch which is essentially what we're going to do and then we're passing in this other parameter which is our payload and this is what the parameters essentially are for the action that we're performing so instead of having a bunch of different callbacks one for adding it to do one for editing to do is completing to do is deleting two dues we just have one single function dispatch and it takes in different actions and different parameters based on what you actually want to do so let's take a look at another example which is going to be for completing a to-do in our list we can just say down here case actions dot toggle flips toggle to do let's make sure we put that up here toggle to do toggle to do just like that and this is going to be our action for either completing or uncompleted are to do so it essentially marking it complete or not complete and come down here first let's print out our to Do's so we can loop through all of our to Do's so we can say to do is dot map each one of our two dues and I just want to create a to do component so I'll say it to do going to have a key which is equal to to do dot ID now we're going to pass down the to do as well just like that so let's create a new file called to do a s and if you just type RFC for this you can create a function component and that's because I have an extension installed called yes seven react Redux graphic you'll react native snippets it's really helpful if you don't want to type out a boilerplate component every time so now with that out of the way we have our basic to do here and it's going to take in a to do now inside of art to do we're going to have a span and this is going to contain art to do dot name just like that and we're also going to give it a style and this style is going to be what happens if it's complete or not complete so we're gonna set the color based on to do complete and if it is complete we just want it to be this really light gray color and if it's not complete we're gonna make it completely black just like this there we go let's put this on a new one so it's a lot easier to read there we go and then we're going to have two different buttons and our buttons are going to be for toggling are to do and completing so we're gonna have toggle and delete here and we don't really know how we're gonna handle the on click for these buttons yet so let's just leave them like this for now we're gonna say you for both of these and of course we got an error because we need to import to do so come up here will import to do from dot slash to do J s and again we're getting another error and that's just because down here we need to make sure we return this from our map and now if we save we should see that if we type something in hit enter we got that added as a to do you can type something else in and again we're getting that added as a new to do now that's left is to handle our toggle and delete functionality so it's right in our toggle functionality inside of our reducer so what we need to do is we need to take all of our current I Do's and we need to map over them to get a new list of to do's and we didn't take the current to do that we've toggled and set that to complete or uncomplete depending on what it currently is so we can just say we're gonna have each one of our two do's and here what I want to do is I want to take a check to see if our to-do ID is equal to the current ID so let's pass that into the payload you can say action dot payload ID and if that's the case I want to get a new to do that is complete so we're going to take our to it current to do and spread it out so that all of the values in our to-do are in a new object and then we're gonna set complete equal to to do complete what we want to negate this so it's the opposite of to do got complete this is essentially going to reverse the polarity of our complete flag turn it from true to false or from false to true and if it's not equal to the current to do let's just return the to do as is because we don't want to modify it now what we can do is we actually know how to set up this toggle to do we need to pass in to our dispatch function this action as well as a payload that contains the ID of the current to do so a really easy way to do that is just pass our dispatch function down into our to do here we're going to set that equal to dispatch just like that and now when our to do we have access to dispatch and now what we can do instead of our button is we can say on click what we want to do call a function we want to call this dispatch function we're gonna pass it in a type and we're gonna pass it in payload and our payload we already know is just going to be our to do ID we're just passing in our ID as an object but our type is going to be a bit confusing it's going to be actions and we want to make sure we get our actions dot toggle to do and in order to get this actions object we can just import that so we can stay import actions from dot slash fjs and let's make sure we export that all the way up here so we can say export our actions and that we are able to toggle our to do let me just make this screen a little bit larger so it's easy to see so we're calling an onclick function which calls our dispatch with the toggle to do type and it gives us the idea of the current to do inside of the payload so now if I type something in type something else in hit toggle you can see that it now has that light gray color because we toggle it to complete we click it again it toggles to incomplete and we can do this for both of our to do is completely independent and again we only ever passed in that one single dispatch function into our to do here we can do a very similar thing with our delete let's just copy all of this paste it into our delete here and instead we're just gonna call delete to do and again pass it in our ID now in our app let's handle that delete to do you can say delete to do it's going to be delete to do and again we're going to have a case for the leading are to do just like this get our indentation correct and also make sure we put in our default case we're just going to return our current list of to dues so now here if we delete it to do all we want to do is take our current to dues you want to filter them to remove the to do that we don't actually want the one we're trying to delete so we can just say to do and to do ID is not equal to our action dot payload ID so essentially what this is saying is if the ID of our to do is not equal to the payload ID then we keep it otherwise we get rid of it so it'll delete whatever to do we want to get rid of no you can put in some to dues here and if we toggle them that's working as expected and we click delete it's going to remove that to do from our list and the brilliant thing about this is no matter how many different actions we want to support for our to dues for example if we want to edit them if we want to save them if we want to share them move them somewhere do all these fancy things all of that is inside of our one reducer function and when we pass our stuff down to our to-do we just need to pass this one dispatch function and that handles all of our different use cases so no longer do you need to pass in handle click handle complete handle edit handle new handle create handle delete you just pass in dispatch and that is it it really cleans up your props and in general makes the code that you're working with much easier and cleaner in my opinion and that's all there is to the use reducer hook if you enjoyed this video make sure to check out my complete react course which covers everything you need to know about react I'll link that down in the description below and also thank you very much for watching this video and I hope you have a great day
Info
Channel: Web Dev Simplified
Views: 131,003
Rating: 4.9684849 out of 5
Keywords: webdevsimplified, react hooks, react tutorial, react js tutorial, react hooks tutorial, react hooks project, learn react hooks, learn react js, react beginner, javascript, js, learn usereducer in 20 minutes, usereducer, react js usereducer, usereducer hook, react usereducer hook, usereducer tutorial, reactjs usereducer, react js usereducer tutorial, use reducer react js, learn react usereducer, react usereducer js, react reducer hook, react reducer function, react reducer, react
Id: kK_Wqx3RnHk
Channel Id: undefined
Length: 20min 12sec (1212 seconds)
Published: Sat Jul 04 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.