Why I Love useReducer

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

Good video.

I personally loathe the switch case reducers and string actions and I much prefer to use RTK.

You made me realise I could use createAction, createReducer or even createSlice with the useReducer hook.

This way you get clean local state (like in your video), and keep code easier to maintain. :)

👍︎︎ 3 👤︎︎ u/malajubeop 📅︎︎ Dec 14 2020 🗫︎ replies

this replaces Redux?

👍︎︎ 1 👤︎︎ u/tokensushi 📅︎︎ Dec 14 2020 🗫︎ replies
Captions
hello everybody welcome back to my channel I have a very exciting video for you today one that I have been planning for going on two weeks now not every video gets two weeks of planning this one did so you are absolutely in for a treat in point of fact this video is instructing spired from real life experiences and might get a day job and I think so my best video is nothing come from real life experiences just to say that sometimes I just have fun playing with new technology like my reactive ink video but this one is all about react specifically hooks but even more specifically about the use reducer hook and the title is video which already you know the title which is not always the case when I make these videos is why I love use reducer I have fallen head over heels with the custom with the react Hulk use reducer and in this video I'm going to show you why I think it's an amazing hook and how you can leverage this reducer to make your components as easy to manage and update when you have complex state that are inside those components without any further ado I am getting excited to start showing you all about why I love and soon you will love use reducer okay so what I have here is a very basic example component one that you may have built yourself in the past these styles as always are the most lovely styles that any developer has ever made but it is your tried-and-true login form a piece of UI that is always deceptively more complex than I think it is and one that is very deserving of use reducer but then I'll come little bit later we're gonna build up to it before I actually show you why these reducer is great so this is a basic UI thing this is the component here by default it's not really doing anything yes because we actually haven't had to edit any functionality and because we're using hooks in this example what we need to actually have the first time actually start hooking this just raw UI component up with just a new state this is gonna be my first attempt at adding state to this function component and to do that I'm gonna use you state which is very similar to a class components State mechanism as well so I have two pieces of data that I want to hold here when is a user name set user name I'm gonna say you state and the default state's gonna be an empty string gonna copy and paste that to try to speed things up a little bit I'm gonna say set password so now what I can do is have these be bound just like anything else that you do with a react component so this is user name I'll save that on change we're gonna say II set user name to be e current target value cool so now when I change this it's being updated and I have it in local states let's do the same thing for password something this is going to be password and again this is going to be password as well so now we're able to update our state and now these input elements are control elements something that you have probably had experience with if you've done react in the past so now that I have my state under control I can actually start building out the on submit button I actually have my usual name and password that I can actually submit things to so for here we're going to actually import I actually have a pre-built little local helper utility to actually log in from utils and this is a pretty basic function that I made that kind of emulates a API called I've hard coded in my usual even password so only if my user name is Harry and my password is the top secret password of password well this actually resolved successfully otherwise it will fail so here what I can do is rather than having it via to do I can say wait and login and pass in the username and password and I don't want to see the pastor thank you Chrome so now when I do this I want to actually show whether it was successful or not and the first way that I can do this is with a loading indicator actually show that things are being loaded so I'm going to another piece of state saying is loading set is loading and the default state of this is going to be false by default it's not loading what I'm gonna do is when the function is first called missed set is loading to true and then when it's done all set is loading to false and then I can actually use this to then update my UI with it so I'll go down here and I'll actually make this button be disabled if it's loading so I don't actually let somebody do double requests and here I'm going to say it is loading I'm gonna say logging in and it's not I'm just gonna say log in so now when I do this logging in and it never stops that's because I made a boo-boo because if it fails it's gonna throw it's gonna reject the promise and with async/await I need to actually catch that if I can so here I'm gonna say I'm gonna catch it do nothing for now save that now when I login login login now that's cool however if there is an error I want to actually show the errors let's do let's add that state as well so the error is gonna be also a piece of text when I say error set error blank by default and then we have here when it's a set error is incorrect username or password and that should be what we have for now so I mean login Suites we're not using that haha gotta use the error message so I use the our message right above here to sell tell the user that we have a little su issue right here error peanin class name error so if there is an arrow if you show the error supposed to login and then we have in characters name and password now let's do some other using and password if you log in well that should be hidden right so that's actually like you know when you first get on submit will say set error as an empty string to actually have our state update as we wanted to be there now if I do it again goes away cool so I'm updating that but also when there's an air out Swansea when there's a success so I'm gonna say if there's a access success date so is logged in set is logged in by default it's false and if you go down here and you succeed they'll say true which is sweet and if I'm logged in what I want to do it's rather to show that for I'm gonna say it's locked and I'm gonna say h1 hello username cool otherwise we're going to just show the forms down there question mark ternary I gotta close the fragment sweets so now when I do this this I got an error I put in a new username hit enter it goes away the password and because I used the wrong actions see this actually here so now I log in with my credentials a parry and password I get logged in just great but I also want to have a log out button as well so let's add this so we're going to add a button that says log out and then on click we're going to say set state nope that's that state we're gonna say set is logged in to false cool so now I log in you pass for it I can log in I can log out oh but now when I log back out that I also have to then clear my username password because those should be persisted at all that's Delphian mistake so I hear what I could do if I say sentence logged in I could say I've set username to be blank said password to be blank also we don't want actually show an error message if there's already an error message there you don't we shown that so now I fixed that bug but I'm by doing all this stuff in my on submit function that seems very unnecessary password I got again cool so that's kind of making the login plain using just raw you state and it works and it's fine but it's trying to grow Brill a way where I'm doing all this really imperative say okay long submit I have to set this loading it's true I just said error is this then when I log in I have to also say set his login is true that username I'm dealing with all these state transitions well what I really need to worry about is the action that the user wants to take on my locking component all I care about is starting to sign-in trying to start logging in and they're starting they have a successful login that would fail I login and they also have a sign out so these are the kind of like four actions that a user is going to actually try to take with this lock an app and right now I'm not like thinking about you know the behaviors of my user I'm thinking about the minutiae of state changes in my application this is a very subtle point the one that I want to stress because this is where my love for user user really kicks in is that with you state you think very much like if this I have a thing that can either be a or b I control what it can be to be true and be false but as a user they're not really thinking about true or false they're thinking about what they're trying to do these are trying to login cool what does that mean in terms of the actual state value they don't really care you shouldn't really care to be quite honest when they have a successful login they want to see what happens then and there's kind of like this this two-part process there's there's how a user thinks and how they interact is a component and what they can put a house to do underneath the hood to actually make that become a reality and when you use you state your thinking just in that raw state world the one where all you have to worry about is just state changing not really worrying about what a users trying to do any application and this is where use reducer really comes into play it really shines so let's actually migrate this component from all these there's what is it - for five youth state usages into just one use reducer usage okay are you ready to learn some more fun with use reducers so we have all these state instances and what actually first thing to do is input use reducer you reducer takes two arguments and returns an array of two values whatever turns is your state and returns dispatch if you've ever used Redux in the past this should look familiar because it's ideas directly inspired by redux and then use reducer takes two arguments the first one is the actual reducer that actually tells these reduce or how your straight transitions should happen and the second one is the initial state so for now I'm gonna have a lager reducer so wanna copy this and I can actually define the log and reducer outside the context on my component and then this takes in two arguments the first one is the state the current state and the second one is the past in value you're actually calling dispatch and just an aside the reason why it's called reducer is because it follows the same API as dot reduce those fun trivia phenomena straight turn state and the second argument here is the initial state and that's kind of what is the initial value set in use reducer from here the initial state I'm actually going to steal all of this so I'm gonna go here this is be using my theist code kung-fu to speed up this video a little bit so as loading it's going to be a boolean and default to false and it's logged in as also when you default to false cool so now it's kind of neat is that if I want to right now so now let's keep the Leon the log of reducer let's actually do myself a little bit more space so log reducer sorry that you actually now can update things of these reducer if you start thinking about the behaviors of the user rather than the state changes so for example what I first want to do is make it so that I can actually update the is loading state let's start there and a common practice with reducers one that I actually prefer is switching on the actual action coming in by convention there's a type property on an action object which is just a convention you're not actually required do that and we're gonna have a of login then here a return is a copy of the current state I wanna say is loading true so I don't here right now is I mean the first kind of action for our little component here which means the action that he used to try to take is to login and when a user logs in the action I can now then think of the minutia state changes in my reducer which actually let that become a reality and the first one if I just copy from here it's doing set errors MD and shoulder is true so as loading is true I'm gonna say error is being reset to false and right here I actually have this one location where anytime anywhere in this component I want to login I can just have it be done here so what I can actually do here is change this and make it feet dispatch this is an object where I can actually get string to for long to be another be just login I may use this for now say actually type is login so now when you hit on submit I'm dispatching the user behavior of logging in and then divorce decouple financial component is what the actual state changes are from there so let's actually keep moving that around so this is login we're gonna say set is letting bottom two and actually have that be called success so it's actually move that over here so i'm gonna type case success we return again copying or the old object because whatever you turn from use reducer is the actual value that is wherever you return from logging reducer from any part of the function is what state is updated to so I want actually copy over the existing state but just modify certain things this case I want to say set logged in is true it's gonna be is logged in is true I also have an error state from down there let's copy and paste this say error and when there is an error what I want to do I want to do three things for things so Wow I want to say it's a dispatch error so I want to set the error to this value so error becomes nuts I want to show loader as false so show loader is false or actually sorry is loading I need that very poorly and then I want to zero out the username and password fields so I go here and say username password then also I need to have one other one which is when I log out it's gonna have that be dispatch type of log out then up here very very much true here I can go case success and then log out is logged in becomes false cool so already you can see things get kind of easier to read we're on submit I have three actions that you can take login success an error that's very much true or user where they're taking an action on your component so let's actually start using these values I'm actually going to do a little bit more kung-fu I'm actually gonna take all these actual values from state and then just the structure them off of the state object there oh I forgot to actually update these here were actually getting the values actually what I can do here is kind of make a meta dispatch where actually that I can do dispatch type is field the field name in this case is years the name and the value a lovely little e current targets value like that such like copy and paste that to be in here and now we can actually do don't touch me password is handle it just right now when I try to type which I'm trying to do right now nothing's happening because we actually haven't handled this actions let's add field return states now we're actually gonna do some nice little es6 interpolation of a property field do that so now let me type in entering update i log in look at that incorrect username a password if i do Harry password don't tell anybody else my password we logged in and look we log out things are looking good oh but my log out this is still here oh I guess I forgot to copy that over when I was doing this migration so when I log out but I actually I can do here there's actually just copy and paste this and like right here I'm not like thinking about where this is happening the UI I'm thinking about where it's happening the reducer where the actions heat happening I could have this I could dispatch this action anywhere in the entire component and how its handle will be consistent everywhere and that's kind of like the real magic of use reducer is that you don't actually think about state use anymore you think about user behaviors do you get to dispatch things that easy wants to do then internal to use reduce or handle these complex state changes because this gone this is messy real quick for example logging forms can get much more complicated in this you have a reset password flow that might want to change up the internal to here so you could have to dispatch up the reset password' potentially switched to a social login to be able to log in through there you have a lot of complexity in there whereas here you kind of just think about in the component you gets interesting about actually use your behaviors the the what is I like to say you get to think about what user wants to do in your component with dispatch behaviors and then how that happens is all centrally located in your you and your reducer and yes the file itself might be a little bit longer but I would strongly argue that this is much more maintainable than having multiple you state implications in your component right now you know that when you log in is loading is true with an error is empty I could even be that you can actually think about what the state should be and move things around here if you wanted to say you know case login you know is login should never be true that's the case if you wanted to do that just be extra safe you can just add this here now you've added a little bit more stir state management into the things there so that's kind of the gist of it hopefully that made sense and you learned something from it because I think it is one of the most incredible hooks in all the hooks available use reducer lets you really separate the what the user wants to do from how your component can get it done even better you can actually have you wanted to you could share reducers around you really want to and also in many ways use reducer is in no ways a replacement for redux redux has a broad application level purview that has things built in lots of scale but your whole application so to say that use reducer could replace redux is not entirely affair to redux if you have to do a lot internal to a component that you might otherwise have offloaded to redux but to say that you can replace all redux just with hooks they're usually do serve Huck is probably a little bit too eager on this current point in time I'm very curious to hear your thoughts if you have played around with the introducer and it be first to hear what you found as well because I think it's a very exciting and powerful feature this is just one example that I found it just really shine above all else let me know what you think in the comments let me know anything about a video you're not already a subscriber to please become a subscriber and join this family here of tutorials and videos and my days looking at you hopefully give you some joy in life and entertainment as you go about your day floating away into the dark dark alright it's been a pleasure you today hope you enjoyed video I will see you again next time
Info
Channel: Harry Wolff
Views: 63,358
Rating: 4.9577837 out of 5
Keywords: react, hooks, tutorial, code, react hooks, usereducer
Id: o-nCM1857AQ
Channel Id: undefined
Length: 22min 40sec (1360 seconds)
Published: Mon Apr 29 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.