Learn React - useState

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello my name is Eric I'm a software engineer I found often times when using a new library or trying to fix a bug I skimmed the documentation I'm guilty I'll speed read or I'll search just to find out one piece of information that's going to help me do whatever it is I'm doing and move on to the next step but I don't like that in this video series I'm challenging myself to slow down breakdown coding examples and really deep dive into documentation that folks have spent a lot of time and energy on so that people like me and probably you can utilize their library to its fullest extent welcome to documentation Nation hello documentation Nation we are going to be looking at the the new react documentation today uh still uh in beta according to the uh the URL here I believe I mentioned on a previous stream or video somewhere that I was a little frustrated with the react documentation because it was still using class components versus functional components so this is the update it's been out for a little while I don't remember it specifically when it came out but um haven't really looked through any of this and um we'll be doing what we can today to just go through something a little bit familiar I'm going to go through use State documentation here I've used react for a lot of my projects I really enjoy coding with react uh and I'm very familiar with you state it's it's everywhere so let's go through the documentation and let's uh let's take a look here and just go through some of the exercises that are given or just play around with it and see uh how we go through this so I'm not going to go through installation um but I I believe there's two sections in here there's a quick start section which we can go through um which has some creating components nesting components which I'm not going to do specifically there's a state section in quick start but I don't know that we should do that because I don't really want this to be the quick start thing right like we've got using hooks we've got sharing data between components we've got state in here but when we go to managing State managing State really is is what I'm interested in tackling the more in-depth stuff which is listed as an intermediate uh I'm not sure what their rating system is here right here we've already got kind of the the hint that uh State isn't to be duplicated within our application so um we're gonna learn about how to think about UI changes how to structure State how to lift State up and control whether state gets preserved or reset consolidate complex state logic in a function how to pass information without prop drilling which is super important right I kind of get lost in that myself where I do excessive prop Drilling and trying to get better at that how to scale State Management as your app grows so let's the first thing I'm going to do is I'm going to um in this I'm going to install react here we're gonna we're gonna make a new I'm in a folder I'm going to make a new file here or the whole setup right and I'm going to not use create rack react app I'm going to use Vite latest uh let's call this use State Docs and let's use react and I'm gonna the documentation doesn't use typescript but I'm going to use typescript uh just trying to keep myself in the habit of using it all right let's start here with react you won't modify the UI from code directly for example you won't write commands like disable the button enable the button show the success message instead it will describe the UI you want to see for the different visual states of your component initial State typing State success State and then trigger the state changes in response to user input this is similar to how designers think about UI there's a quiz from a quiz form built using react to know how it uses the status State variable to determine whether to enable or disable the submit button and whether to show the success message instead so I've got my Source over here let's go to Just app.tsx and we can also we can get this running right now and I'm gonna end up just clearing out a bunch of this starter code and here we go we've got our basic counter step in here and then we're just gonna we'll just pop out right now I'll keep this app container but I'm gonna get rid of everything else so here we've got a quiz in the documentation here we see their import use state from react where they export the functional component we got three different state here three different use State commands so we've got answer and set answer error set and set error um it's just a quiz so in which city is there a billboard that turns air into drinkable water and then whatever we type in here we're going to get wrong but good guess but a wrong answer try again right so let's look at the the jsx first right we've got um the whole thing returns there's our H2 the city quiz here's our paragraph with the question and then I wrap this in a form right your text area and your submit button um we can see they tie value of the text area to the state of answer we can see they have an on change that calls the function handle text area change and then they have disabled equals uh status triple equals submitting in quotes there right so let's go uh and they've got a on the whole form they've got it on submit but when you click that submit button right which is working because they have this button can I scroll anymore they have this button wrapped in those form tags the button's disabled here right if answer dot length which is our value answer is tied to whatever this form value is or this text area value is so if that's equal to zero or if status is equal to submitting right we're going to see what changes that status in a minute and then they've got some error stuff here so let's go look at the functions that are written right here's handle text area change which passes in an event right which we look at the text area the on change handle text area change so they're passing in an event here and then set answer which is part of their use state for answer right it's their Setter function they're just passing an e.target.value so whatever the value is of what we're typing in that that field so if we look at the actual handle submit their e prevent default right you know we have something wrapped in a form and we hit a submit button it's going to send out that request and it's going to refresh that page so we don't want that to happen set status to submitting so that's where that submitting comes in right as soon as you click that button status which defaults as typing they're just changing to the string of submitting uh see us as soon as we and status is disabled right if you know this is gonna this is gonna equal out the true right this this JavaScript status triple equals to submitting once that equals submitting when we initialize that function that's going to equal true right so let's let's see how that looks we're typing whatever right we'd still submit as I click submit you see all this Grays out right that's on text area and and the button itself so as it's submitting when it when we click that function it changes to submitting and then they wrap this in a try catch where there are weight submit form answer and if it comes back correct and we get a success set status to success otherwise we get an error which is this down here that's displaying it sets that as set back to typing they set error to whatever the error is that they're receiving so we don't get to see the submit form function right which is just I guess oh nope here it is actually towards the bottom so here's the submit form function that we saw which takes our answer which is the state we have here turns a new promise there's a timeout so this this isn't actually calling out anywhere right this is just kind of simulating what could be a call out to a server somewhere um well we can see that you know what should error equals answer to lower case if it doesn't equal Lima then we reject with this right so if I type in Lima here now it should give me a positive affirmation here that's right cool so that's that's how all that's working which is fun and here's our timeout in milliseconds um so it's just taking 1500 milliseconds before it actually returns that promise and they take that promise and they within their try catch and if it's success and they throw that success in there for us and they give us back our um but let's go look at what everything should be with the success where does where does that's right come into play here so here's the that's right message right which so this whole thing then this is a different return statement right so in in their use case here in their example if status comes back with success which is what we saw down below uh in the case that our our value matched our answer me to Lima then we have our return statement here which just is an Asian one that says that's right so that that if statement is just being passed over from the beginning right because that status is set to um typing until we get that positive answer until we get the correct answer back and then in that uh in this try catch it's being set as a success and then we hit this statement right and then this return is an even hit because we can only have one return of this functional component so you're either going to have this return which is just the H1 or you're going to have the return statement with all this jsx in here so cool all right we've we've taken a look at that we understand the code that's there we've read through the code that's there we look through all those functions and uh it's all making sense to me I don't know if they expect a newcomer to this to to read through this and and fully realize what all this is doing but it all makes sense and it's a it's a pretty good example of of how to use you state on a number of different things here it's a pretty clever example choosing the state structure structuring State well can make a difference between a component that is Pleasant to modify and debug and one that is constant so a constant source of bugs the most important principle is that a state shouldn't contain redundant or duplicated information if there's some unnecessary State it's easy to forget to update it and introduce bugs for example this form has a redundant full name State variable I'm not coding anything yet I wonder if I should make this full screen you know what it might be better to do than scrolling up and down through this I think it's going to be a little better if we let's copy all this stuff right um well let's or let's start typing out some code right so um we know when we're using react that's not explicitly stated here in in the documentation but we should have inferred by this point that we need to import you state from react before we can actually do what they're describing here let's put in our U state right we're going to do const they've got here first name set first name equals use state starting off as a blank string they've got three of these things last name oh I see the so where we're going to type some of this stuff out right just to kind of see the example here of redundancy and actually this is a this is a thing that I definitely did when learning react the first time around um and handling forms and things like that so we've got set last name and then they've got full name and set full name and we can see each one of these is starting as a blank string that's our initial State value and they've got a function here which we'll go back to in a minute to handle all these changes right I don't want to just type this out bottom of the top I want to explore this code a little bit more here's a return statement I I can copy this I don't need to type every single one of these things out but we've got well let's let's copy the return statement and let's take a look at it in our code here in our editor so we've got well I don't need this oh no I don't need this um fragment because I've already got a container so we've got some errors here because I didn't set up those functions yet and that's okay let's get rid of this let's give this some room to breathe let's word wrap this thing so in here we've just got nh2 let's check you in I know we've got a label with an input right so they're wrapping their label around their input you might see this you know with the html4 in the label and these things separate it's cool to do it this way um the value tied to the first name state it's kind of value times the last name State and then a paragraph with your ticket be issued to full name right so no let's go let's go look at the actual um functions they've got here right right they've got function handle first name change e Let's uh type that incorrectly first name change e which is our event which we can look at Let's uh let's do that first and let's we'll do the last name change we'll just do the same exact thing oops handle last name change right and here's our form the formatting is totally different I don't care right now that's fine um and let's look at what's going on here right so we've got our first name and last name fields they are blank at the moment we're starting off with a blank state if I were to have put something in here make our first name if it has the value of tests to begin with that's going to show up right because we've got our value is tied to the state of first name if it isn't tied to this data first name Let me refresh this now we've got nothing in here right so when you've got your forms you need to make sure that your value you have a value listed that is tied to whatever your state of that particular input field is going to be so we'll drop that back down to a blank value same thing with last name and in your ticket will be issued to full name which is over here which we've got nothing showing yet because we don't have a value for full name right and we do have this on change function which calls our handle first name change function and as soon as we start typing in here now we can see here's our event which is all sorts of fun stuff in it and what they are calling is e.target.value right so if we look down here we've got Target which is our input because this is the event that's happening on this input and here's our value I think we could see they have set first name that's e.target.value set first name e.target dot value right so anything that comes through is that value is going to update with our Setter function so now if I want to I want to reset this because I want to I want to look at this again with our log that we call in right so um we've got Target and I want to call attention to this now right so now we see the e in there because we've tied our value we've got our Setter function and every time we call that update I'm gonna drop this down to e dot Target dot value so we can just really see what's going on here right so every time we type in something that value changes e.target.value and it's going to our Setter function cool and let's close that so I don't get confused and then they're doing set full name so you can see they're doing set full name twice in both of these things e dot Target dot value and we add the last name either target.value we added first name um and as we type then both of those things are going to update right so let's just copy this over and save ourselves some typing same thing with this actually I'll call both of these because I haven't updated that yet so now as we go through here I don't really need my console anymore I'm not logging anything and we can see as we type foreign gets his name appeared below but this is a bad example of managing state right and this is this is what this is going to tell us so you can remove it and simplify The Code by calculating full name while the component is rendering so what is it saying for us this is just giving us instead of full name as a state it's giving us full name just as a value right and the reason that this is going to work for us is and let's let's see what does it tell us it doesn't tell us here so I was looking through the documentation here to try to find a specific call out to why they're recommending managing State this way right or or you know getting getting rid of the set full name and getting rid of that state completely and just using a const value right using a constant which you know makes sense right this is this is the way this should be handled because you're you don't need a state for for full name when you can calculate full name based on first name last name so let's get rid of that right and let's you know we we see that this is going to work the same way if I do David David again we see that it's working the same way um but I don't really see a good explicit explanation on the Y which is all about re-rendering right when you have a component in react and the state changes we have a we have a state changing it re-renders that component let's let's do a little display on this right so if we just kind of console about log um you know I have rendered and we inspect this this isn't in a function right this is just I just have this as a just as a console.log statement right in our functional component so let's let's clear this out let's refresh we see we get I have rendered I'm getting a duplicate here because of uh react strict I think is on uh let's let's go adjust that real quick because I don't I don't want that let's get rid of strict mode so we only see this one time okay so our component loads we get I have rendered I type A D we have I have rendered I type a v i d we're seeing multiple console.logs here right every time I type in a letter we're setting State and react is re-rendering the entire component if you have one tiny little box of a component that we're rendering you don't need to re-render the entire page so you can update you know your UI way more with way more specificity right and we can we can show this let's make a test input dot TSX component and we can set our state here like we did in the other we could do const test State and set test state equals use State and we'll do the same thing as a blank string our value here is going to be tied to our state right and then on change I'm not going to write out a separate function for this I'm just going to do we send e over to set test state e dot Target dot value I didn't throw an equal sign in there there we go and if I import this into our rack component here and import test input and we can just throw this right down at the bottom here press to input right so this one has its own state and let's do the same thing here let's do a console.log test input render and over here we'll change this to parent app render right and let's go look at the logs here so let's let's clear out everything that's here and let's refresh so we've got parent app render and test input render right as both of these things appear for the first time each time I update now the entire thing we get both parent app and test input render right because that test input is a child component of our parent right so everything is re-rendering every time we have a state update but if I just this is our tests input this is this is this input down here so now if I just make an update here now we're just seeing test input render that's the only thing now that is re-rendering right so um I I'm missing that from within this documentation here right where it says um where we've got this lesson of we don't need state for this thing we can just calculate it and it's going to update because of the re-render process it says that you can remove it and simplify The Code by calculating full name while the component is rendering which is true but it doesn't really explicitly state how rendering works here or linked out to something else that explains it which might be helpful for some folks who are new to the framework but there you go hopefully that was helpful uh in in understanding why they're suggesting that we do that sharing State between components sometimes you want the state of two components to always change together to do it remove state from both of them move it to their closest common parent and then pass it down to them via props this is known as lifting State up and it's one of the most common things you will do writing react code in this example only one panel should be active at a time to achieve this instead of keeping the active State inside of each individual panel the parent component holds a state and specifies the props for its children so here's the state that they've got they've got active index at active index which defaults to zero and in their return statement is all of this fun stuff that we're going to look at in a second and I copied that last bracket all right let's get rid of this so here's what they've got here right and if we're looking through this thing we've got our H2 we've got panel here title about is active active index is equal to zero a little bit confusing way using active index and set active Index right when I'm thinking index I'm thinking these things are in an array of some kind but it's not necessarily the case right you can you can set this up however you however it makes sense to you but what's going on here is we've got the panel right this is the panel function this is the child this is the parent that we've got up here and these are the props that are being passed in this has given me all these errors because I don't have I'm using typescript I guess I probably shouldn't in this case but um I'm not declaring what any of these things are so let's look at function panel first right this is a component on its own this is our return statement which are breaking this out into section which is fine last name is panel don't really care about that H3 which is the title proper passing in thinners is active internally operator here and if it is active if that's true then children is displayed in paragraph and then there's a button if it's not active right this is the the opposing if if else kind of statement here right if active is true is active true then display in paragraph the children otherwise display a button that has an on click of the show which the button says show this is our button and the on click command what does that do for us calls an anonymous function which sets the active index on this particular one to zero and on this other panel component on show calls an anonymous function that sets the active index to one so if I click on this this is the about section that isn't showing right now clicking on this button call set active index and updates that state to one or to zero in that case sorry this show button sets that active index two one is active it's passed in and this is only this is only going to be true if active index is equal to one right so we've got two I'm going to separate this out a little bit more to really see what's going on here because panel isn't something that you're typically seeing right in regular HTML panel we're using panel because this is the component right so let's let's build this out and let's let's add another panel in here and really see what's going on so we've got panel let's make our own panel and we've got a couple things here that are passing being passed through as props to panel all right we've got title which we're going to call this our test panel we've got is active which is just a prop that we're passing through we've got active index we're going to set this for our case we're going to set this to 2 right they've already got zero they've already got one you could call this anything not Index right you don't need to call this you could just just call this active number if you really wanted to it's got an on show prop which is just a function that we're passing in right we call Anonymous function we call our setter active index and in our case this one's going to be 2 right oops for some reason my own show came out let's put that actually in make sure that's and it's a prop right and we've got our test panel down here right which we don't need to send in the button right that button's already there for our test panel because that's part of this component right here and this is the ternary operator that's saying like Okay active index is yet to be set to 2 so don't don't display children and Children Here is literally just this stuff that's in between our two panels right are it's it's inside of our panel component here that we're listing out this way right so here's here's children here's a text uh whatever we list here is considered children right when you've got your opening and closing brackets on your components anything inside is children and can be passed through as a prop right rather than making this a children prop which you might also be doing this is the alternative right rather than using that just listing our children prop in between is a little bit cleaner a little bit nicer to read so now if I click this because we're in our on click is already being set here right on show we've got our on show function that's being passed in so now we've got this here whatever we list here is considered our children and we've set that so we were we're reading that example we're understanding how that works um a little bit of uh separation help this kind of visualize this a little bit better and this is another thing that you know I don't know that um you know it's it's really just talking about State being set at an upper level it's not diving in here um to how this is working so I'm I'm happy that I'm going through this and kind of diving and digesting this a little bit better um helping me you know get better at the process of reading code and understanding code and becoming familiar with a different code base that isn't my own granted this is a very small example but we're able to talk through it and learn a couple things preserving and resetting state when you re-render a component react needs to decide which parts of the tree to keep and update then which parks to discard or recreate from scratch in most cases reacts automatic Behavior works well enough by default react preserves the parts of the tree that match up with the previously rendered component tree however sometimes this is not what you want for example in this app typing a message and then switching the recipient does not reset the input this can make the user accidentally send the message to the wrong person in this example it's saying that if we type something in here and then we switch that that state is not being reset so react lets you override the default behavior and force a component to reset its state by passing in a different key like chat key equals email this tells react that if the recipient is different it should be considered a different chat component that needs to be recreated from scratch with new data and UI like inputs now switching between recipient always resets the input field even though you render the same component so let's let's see what's going on with this one now so here we've got chat with key is tied to the state right as opposed to before it doesn't have a key at all um normally you're going to use Keys when you've got you know you're mapping through data right which is what's happening over here on the contact list .js file compact set map right this needs a key so react and kind of keep track of what each of those components are so in this what they're doing is they're assigning a key to a component that's not being mapped that otherwise wouldn't be re-rendered when we change State here this this contacts when we look uh where where here's our contacts right and we can see it's an array and contacts is set to the default of zero right is it an array zero so index zero so this is our default Taylor with email Taylor so the chat the key is set to whatever our two value is dot email dot notation email so in the case of Taylor it's set to email Taylor and if we type something in and now I click on Alice now it's re-rendering this whole component where otherwise it wasn't doing that previously so that's a cool thing to know you can force a reset you know because now in our chat JS that state is going to reset back to whatever your default value is otherwise that's going to retain State because previously this wasn't going to re-render right well that's pretty cool we're going to stop here for now hopefully this was fun to follow along with and it's been nice for me to just dive into documentation see you for the next one
Info
Channel: EricWinkDev
Views: 99
Rating: undefined out of 5
Keywords: react, reactjs, usestate, documentation, how-to, how to, javascript, typescript, code along, code with me, code, programming, programmer, webdev, web development, developer, software engineer, software, engineering
Id: jUcs4Dfox50
Channel Id: undefined
Length: 36min 0sec (2160 seconds)
Published: Wed Dec 21 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.