React Hooks | useReducer vs. useState

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this video we're going to be taking a look at the used reducer hook in react in the reactant tation they describe use reducer as an alternative to you state now it's interesting to note that use state is actually built from use reducer so with use reducer we can actually achieve the same results as with use state so then when would it be preferable to use use reducer over you state well again looking here at the docks they say use reducer is usually preferable to use state when you have complex state logic that involves multiple sub values or when the next state depends on the previous one so whereas you state might be better for dealing with primitive values like numbers or boolean Zoar strings if we're dealing with a more complex data type like an object or array use reducer might be a better choice also use reducer might be a better choice if we have multiple state values changing upon the triggering of a particular action like a button click or a mouse-over event for example a lot of the difference in my opinion comes down to the way that use reducer allows us to write our code and therefore reason about our code when we're dealing with more complex data types now what I'm going to do in this video is I'm going to show a side-by-side example between a functional component that uses you state in a functional component that does the same thing but uses use reducer and we're going to start writing out some code in a second but first let's just talk about the big idea of reducers so a reducer essentially is a function that's going to take in some state in depending on an action or an action type that it receives is going to return a new state and if you've worked with redux before the user reducer who can react is basically the same as when you write a reducer in redux the user reducer hoe can react though is not the same as the entirety of redux itself because with redux you're using reducers in conjunction with global store in order to mimic that with react hooks we need to use use contexts in addition to use reducer but this video is simply going to talk about the use reducer hook on its own and show how it can be used to manage perhaps more complex state locally in a component all right so with all that being said let's get into an actual example so like I said we're gonna start off with a stateless functional component and we're gonna use the u s-- state hook and then we're gonna make the exact same example but we're gonna use the use reducer hook so let's get started so what I'm gonna do is I'm going to make an h1 and I'm gonna have that h1 display a guitar so let's check that out in the browser there we go nice red guitar kind of looks like a strat a little bit now what I want to do is I want to create some buttons one when clicked on will add additional guitars another one when clicked on will remove guitars and a third one that will reset the number of guitars so in order to do that we're going to need to work with state of course so let's bring in used state import react and then use state from react and we'll go ahead and we'll call you state and what we're gonna pass in here is we're gonna pass in a number which we're gonna set initially to 1 and that's going to represent the number of guitars that we see displayed on the screen so we're gonna do structure that off of you state we'll write Const create our array and then in the array will refer to that piece of state as num guitars number of guitars and then when we click on one of the buttons we're gonna call set Nam get ours and depending on which button we click that'll either add to the number of guitars that we see subtract from the number of guitars that we see or reset the number of guitars that we see back to this initial count of 1 so in order for this num guitars piece of state to actually affect the number of guitars that we see on the screen we'll wrap this guitar icon into a string and then we'll call the repeat method on it and of course this entire thing is going to have to be wrapped in curly braces so it can be evaluated as JavaScript so the repeat method is a simple JavaScript inbuilt method that will repeat a string value depending on the argument that we pass in which be a number so let's just say for example we passed in the number two was saved we went back to the browser and now we see two guitars but what we want to do is pass in num guitars as the argument because whenever we click on one of the buttons that we're about to set up those buttons are gonna call setting on guitars and update the nama guitars piece of state and of course this whole example that I'm going to show is a pretty contrived example but nonetheless we're showing concepts here we're showing how to use the API and you can take these nuggets of information and extrapolate into your own projects so with that being said let's go ahead and we'll set up three buttons the first button we want to add a guitar with the second button we're gonna remove a guitar and the third button is going to reset the number of guitars that we see so at this point we should see one guitar on the screen and we should see these three buttons and there we go now in order for these buttons to actually do something and update the state we're gonna right on click handlers on them and then each of these on click handlers we're going to create a function that's going to call set num got ours and because we want to add a guitar each time we click we're gonna say num guitars plus 1 then in the case where we want to remove a guitar we can simply copy this and do num Qatar's minus 1 and for the reset will call setting on guitars but in this case since we just want to reset it we can just pass in 1 which was the initial state here so this pointer button should work let's go back to the browser let's try to add some guitars there we go and let's remove some guitars let's add some more let's reset and we're back to 1 now I know in this case if we removed all the guitars and we kept clicking remove guitar we'd get an error because we'd start getting into negative numbers and we're dealing with a string icon here but for the sake of this example I just want to keep it simple so I'm not going to deal with that right now just something to be aware of now the thing is what if I want to come in here and add another piece of state let's say that whenever we add a guitar we also want to show a happy face so let's create another piece of state which is going to be a boolean value and we'll set it initially to false and we'll call that piece of state show emoji and the function that will update that state will call toggle show emoji now let's come down here after the buttons and let's make in h2 and in this h2 let's just bring in a happy face but the thing is we want this happy face to display conditionally that is we only want to see it when we're adding guitars so what we can do is we can wrap this in curly brackets we can use that show emoji piece of state which is initialized to false and we can use the logical and operator so in other words if this is false we won't see the happy face but if this is true or show emoji is true we will see it just to test it let's flip this to true and let's go check it out in the browser and we see so let's go ahead and let's set this back to false and let's go ahead and let's use our toggle show emoji function so we're gonna add it in our on clicks here so let's say when we click the button for adding a guitar we're gonna call toggle show emoji and we're gonna pass in true then let's go to our remove guitar button and when this buttons clicked will call toggles show emoji but here we'll pass in false because we want it to disappear and then on reset we'll also call toggle show emoji and set it to false in that case so now let's go test this out on the browser so when we add a guitar we should see another guitar being added here we should also see that happy face emoji show up and then if we go ahead and click remove guitar we should see a guitar disappear and we should see the happy face disappear as well and it does let's add some more guitars shows up again let's reset and the guitars disappear back to the initial state of one and the happy face disappears as well so all is working so far and yet writing these functions here is one way to do it there are other ways to read it of course we could have written a function outside of the return statement and called that on click passing in various arguments and so forth but now that we built this using you state let's go ahead and see how we would implement it using use reducer I've already got a file set up here on the right which I just called reducer JSX and this is the stateless functional component I'm exporting this function and I'm bringing it into the app dot JS file here on line to import reducer from dot slash reducer so I'm going to comment out this code that we wrote before and then down here I'm going to use that reducer component now let's come into our reducer file and the first thing we're going to do is we're going to bring in the user reducer hook import react and then in the curly braces use reducer so within our reducer function we're going to call use reducer and and use reducer we're going to pass in two arguments the first one is going to be function and this function is actually going to be a reducer let's just call it reducer just for a simplicity sake right now and the second argument that we're gonna pass in is going to be an object which is going to represent the state of this component whereas in our app component we brought in two separate pieces of state here using two instances of use state in this reducer component we're gonna have those same two pieces of state num guitars and show emoji but they're gonna live on this object so the first property will be num guitars which will initially have a value of 1 and the second property will be show emoji which will initially have a value of false now just like with you state we're gonna use array destructuring here and what we're gonna get back from this call to use reducer is the state object and we're also gonna get this method which will call dispatch now at this point I'm gonna go ahead and I'm gonna actually just copy this h1 from the app component and I'm going to paste it here into the reducer component and I just realized that I named this reducer which is a component and this reducer that we're passing in as the reducer function to use reducer both as reducer which probably wasn't a good idea but to distinguish them you can see this one has a capital R and this one has a lowercase R so they are two different functions but anyway at this point we should be able to get this guitar icon to appear on the screen but the one thing that we do have to do is we can't just say repeat num Qatar's because now num guitars is a property up and I spelled it wrong here should be guitars at 1 T so num guitars is actually a property now on the state object so we're going to have to refer to it as state dot num Qatar's right and num get ours is initialized to 1 so we should just see one guitar on the screen let's go to the browser and check that out actually before I do that let's go ahead and let's just set up this reducer function here so we could say cons reducer we'll make this an arrow function and we won't do anything with it now we'll just have it there because there else this is gonna throw an error so this will be filled in in a second well let's go to the browser and make sure that we see one guitar cool so it's working and now back to UVs code let's go ahead and set up our buttons and we can again copy these from the app component we'll paste them in here let's leave these on click handlers but let's get rid of everything inside of them for now and for now let's just put some entierro functions in here which we're gonna fill in in a second let's flip back to the browser make sure we see one guitar and three buttons there we go now let's get on to actually writing our reducer that is the reducer with the lowercase R function which is the first argument to use reducer here so the job of this reducer is going to be to take the state that it's given and depending on an action that we dispatch from one of these function calls from our on click handlers on the buttons we'll get a new state return from this reducer so the way reducers written is it takes the state and then it takes an action inside of this reducer we're going to write a switch statement and this switch statement is gonna listen to actions that we're gonna dispatch when we click on any one of these buttons so let's go ahead and set up our switch statement so we'll say switch and in here it's gonna listen for action dot type let me explain what I mean by action that type so let's say for example when this first button is clicked on the add guitar button in this function here we're gonna call dispatch which is coming from here and what we're gonna pass into dispatch is an object with a type property so this first button will give a type of add guitar like that and writing the types like this with all uppercase letters and underscores to separate the words is just redux convention each one of these buttons is going to call dispatch the difference is that each one is going to have a different type so the second one can be removed guitar and the third one can just be reset so this object that's passed into each of these calls to dispatch this object is the action so action type corresponds to you the type property on these objects so this switch statement here is essentially listening for one of these types with that being the case no pun intended we can go ahead and make the different cases in the switch statement so in the case that action that type is add guitar we're going to return whatever we want the new state to be so remember this is our state object now that we want to add a guitar we want to return a new state object with the corresponding changes that we want to make to it so what we're gonna return is an object and the num get ours property now is going to be state dot num guitars plus 1 so that state which is this object is passed in here in that num Katara's property which was initialized to 1 is now going to be 2 when it's returned and each time that this action is dispatched this number Qatar's property essentially is going to get incremented by 1 so now let's go and handle the other cases we're gonna say case remove guitar if we get an action type of remove guitar we're gonna return basically the same thing as we did here but we're going to decrement by 1 and then we have to handle the reset case so if the action type is reset we're going to return an object where the num guitars is 1 because we want to reset it back to what it was initially and then always we need to add a default case in the case that no action type was recognized by this reducer we just want to return the state so let's flip over to the browser now let's try clicking on these buttons and seeing what we get so we initialize number tars to one let's go ahead and click Add guitar that's working let's remove some guitars that's working as well let's add some guitars back and let's reset guitars goes back to one now how about that happy face emoji let's copy over this line here from app dot J s and as we did before with them guitars this is now gonna be state that show emoji right cuz this is living on this state object here the show emoji property here is initialized to false so now if we go to the browser we shouldn't see this so now we want to do is we want to go ahead into these objects that were returning for the various cases and deal with toggling that show emoji boolean value so in the case of add guitar we'll have our show emoji property on the state object be true in the case of removed guitar show emoji property will be false and we'll just copy that cuz that's gonna be the same for the reset case so now hopefully when we click these buttons we should not only see guitars being added and removed but also this happy face being added or removed so let's go ahead and add a guitar and there's a happy face let's go ahead and remove some guitars cool happy face disappears let's add some more and let's reset so as you can see the functionality turns out to be exactly the same as with this app tjs component using you state but i'll uncomment out what we did here in the app that J's component and you can see back to back the same functionality written out in two different ways here with you state here with use reducer so one of the big difference is that you can see here with the app component and the reducer component is that with the reducer we have access to this dispatch method so we're not changing the state directly but rather we are dispatching in action with the type property and then the reducer is looking at that action and its type property and handling it accordingly with these different cases here one thing you can see is that in this example we have our reducer actually living outside the reducer component so what we could do is we could actually make a separate file just for this reducer we can come in here and we can make a new file will call it reducer ojs and then let's go ahead and let's copy this actually we'll just cut it out and then paste it into reducer digest and now we can just export this as a default like so save this and let's import it into our reducer component and we'll say import reducer from dot slash reducer so this reducer that's being passed into use reducer is referencing this function imported here on line two in Aptos let's comment out all the you state stuff we did just so we can confirm that this reducer is still working and let's flip back to the browser and adding and removing every setting all seems to working just fine so as you can see here in the reducer component saving the actual reducer function that we passed in here in its own file has cleaned up this file quite a bit in the actual logic like incrementing by one and decremented by one is not really a concern here in this reducer component we're simply dispatching actions with type properties and this makes it very clear and very readable as to what's going on we can see that clicking on this button dispatches an ad guitar type or remove guitar type for reset type etc the other thing we can do with this is that if we did have let's say child component let's say here in this reducer component we could pass down this dispatch method into that child component and then that dispatch method would be available in the child component to be called with any type it wants to pass in so thanks for checking out this video on use reducer and a comparison between you state and reducer and react if you liked the video please give it a like in consider subscribing to the channel and I'll see you next time
Info
Channel: The Code Creative
Views: 1,345
Rating: undefined out of 5
Keywords: javascript
Id: 8C6NP1Qsi9I
Channel Id: undefined
Length: 21min 5sec (1265 seconds)
Published: Sat Feb 29 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.