Learn to use State in React in 19 minutes (useState tutorial for beginners)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
what's going on pop fam welcome back to another video today we're going to learn all about state and why you need to master the use state hook to level up your next reactor rod [Music] before we get started guys today's video was only made possible by the amazing guys over at skillshare check this out skillshare is an online learning community where millions of people come together to take the next step in their creative journey the thing i love about skillshare is that there are no ads they're always launching new premium classes and they also recommend really interesting classes so before you know it i'm actually no longer watching tv on netflix all i do is watch skillshare while i'm actually eating my food most classes are under 60 minutes so they should be able to fit any schedule whether you're super busy or you've got a little bit more time on your hands i've actually gone ahead and dropped the react basics 101 entire class on skillshare the first 1000 people to use the link in the description are going to get a free month worth of premium skill share and you're going to be able to with that access that react basics which i've uploaded on top of that you're going to get access to thousands and thousands of courses available on skillshare's platform i've actually been checking out a amazing video editing class at the moment by ali abdel where i was actually able to find out how i could use my ipad to add animated handwriting into my videos to level up my production value and now i'm making the best use out of my ipad as well as leveling up my final cut production game so this is just an example of the amazing value that i've got since i've signed up at skillshare and if you guys want to go ahead and benefit from this just like i have then go ahead and remember the first 1000 people to go ahead and grab that link are gonna get one free month of skillshare premium which means that you can access my react basics 101 class it's completely free you have nothing to lose and then after that you can go ahead and continue if you're enjoying what you see on skillshare what's going on guys welcome to another lesson and today we're going to be talking about state so think of state as the correct way of defining variables in react that's my little easy way of remembering it and what it allows us to do is essentially have some memory inside of each of the components which is local to that component for example imagine we had a counter component and it had a plus and a minus button if we hit the plus button we want the count to go up if we want the minus button to go down now how do we keep track of that counter value we use state right now we can store anything inside of state we can store a number we can store string we can store an array data objects and we can have multiple variables inside of our state fun fact previously only class based components could actually support state which is why functional components were limited but react hooks came along and allowed us to use state inside of functional components and we're going to cover that in a future lesson but let's go ahead and jump into that counter example right now and we can see exactly how to go ahead and set up a piece of state inside of react let's go ahead and go back to our code so we're going to carry on where we left off from last time so let's go ahead and assume we had a counter so i'm going to go ahead and code up a little counter here and we're going to say welcome to my counter app and i'm going to have a p tag with a value inside of it so i'm going to get some a simple p tag with a value inside of it and say the count is and we're going to have some kind of count value being stored here right now we're going to have two buttons we're gonna have one which is gonna have a minus button and i'm gonna copy this and i'm gonna change this one to a plus so we're gonna have a minus and a plus now when i click this button i want it to do something i want to change the value of the count okay so i'm to do is i'm going to create a function called const increment and this one is an es6 arrow function and all it's going to essentially do is go ahead and change the count so what we would have typically been used to is going ahead and having a value like so we have let count equals zero and then what we would say is count equals one count plus equal one right and this will allow us to increment and then what we would have is another one for decrement and we'll have minus equal one which takes away from the value okay and then what we'll have is the count is count okay and then what we'll do is we'll say on click we'll pass in our function and here we'll say increment and here i'll say on click and i'll pass in our decrement function okay i'm going to save the app go back and now we can see it says welcome to my counter app the account is oh what's happening here so notice how the the actual web page isn't re-rendering right so you might be wondering but i've done everything correct because i've made it so that the count is now plus or equal to one so you should have added one right um but it doesn't seem to be re-rendering the page and showing us that being on the screen so the reason why this happens is because we need to update things in the react way and that's where state comes in right the reason why we need to do it this way is we need to set up a piece of state where the count variable will live and then every single time we update the count variable we need to do it in the react way so that react can can go ahead compare the new value that you're going ahead and giving count for example if we increment it's going to be plus one if we decrement minus one compare that value using something called the virtual dom against the actual value that is on the screen and then react will know which part of the web page to go ahead and refresh so it's very very important and we're going to go ahead and change this now to make it work we're going to be using the use state hook and we're going to cover hooks in an uh future lesson but we're going to go ahead and use a a function provided by react and it's called a hook and here what we're going to do is rather than defining our variable like this we're going to go ahead and say const square brackets for es6 destructuring so we're using array destructuring here we're going to say but all you need to know is the actual syntax in this case we're going to go ahead and say count and then the second argument is called a setter and it's a function which allows us to modify the value of what is inside of the count variable okay so in this case i'm going to go ahead and the convention is usually say set and then whatever the variable is called so in this case set count so i'm going to say use state and then inside of the use state parentheses you need to go ahead and put an initial value so in this case it's going to be 0 as it was a number but inside of these parentheses you can go ahead and put an empty string you can put an array an object or an object with some values inside of it anything you really want to initialize this and this means that count will initially have a value of zero okay so i can get rid of this line now going back to the increment to modify the count value instead of doing this this is incorrect so this is wrong i now need to go ahead and say set count so any time i manipulate the count i need to use our setter function over here right so i'm going to go ahead and say count plus one so set the count to whatever the count currently is plus one okay and then this is the correct approach okay and then for this one i'm going to go ahead and do the same thing i'm going to say set count to whatever count was minus one okay and this again is the correct approach and this right here is the incorrect approach so this is the wrong approach okay now the reason why this is very important is because when we go through this function not only are we updating the count variable in a controlled fashion because it's only going to update the count variable when we use this setup function but it's also going to tell react okay a value just changed in your state go ahead and re-render a part of the web page and react has a very clever way of doing that using the virtual dom so now i'm going to go ahead and get rid of the wrong code and let's see what happens now so i'm going to hit save i'm going to go back to my app and here you can see if i go ahead and hit plus there we go oh okay interesting so we've got the plus and the minus back to front so i just need to go ahead and swap these around over here so const increment and decrement there we go because the minus should be decrement deposit plus should be increment and we're going to go back to our app refresh and as you can see as i add it adds the number as i minus a minus is the number so this is using a piece of state and it's using the react way of updating said state to go ahead and actually go ahead and refresh the web page every time a manipulation is made to the account variable now we can have as many pieces of state as we want so i can go ahead and have a different one for example if we had somebody's age i can go ahead and change this to be an age piece of state and then for example their default value could be their their age so in this case 26 and then you can go ahead and use that by using set age to modify that value now as you can see we simply use it the same way we would use any other variable so this in a nutshell is how we do it for a functional component so something to notice is that you see when we update the count as soon as i hit refresh the state resets back to that default value now this is a very important point state is non-persistent which means that when the user refreshes or leaves the web page the state will disappear so there are methods to make it persistent and to keep it we can use things like local storage or we can retrieve from a database but we're going to cover that in a later lesson but it's a very important concept to understand that state is non-persistent by default okay so with that said now i'm going to go ahead and show you how to write this exact same component as a class-based component so i'm going to go ahead and create another app component but i'm going to say appclass.js to sort of separate the two and here i'm going to go ahead and do the following we'll say rcc which is our handy little es snippet and then i'm going to go ahead and copy this div so we want the exact same output for this component save it there we go and here we have the decrement and increment function so i'm going to go ahead and copy that code because that is essentially the same and notice how it would belong outside of our render block right so that's where we would put these functions now notice how the const is erroring out so inside of a class we don't actually have variables these are going to be class functions so we go ahead and save and now we've got the increment and decrement now we need to go ahead and set up our piece of state so in a react class based component to do this we need to go ahead and do the following we need to say constructor and then i need to pass pass in props so constructor takes something called props which we'll explain in the next lesson here we say super props and then what we have to do is say this dot state and the state works slightly different in a class-based component it's a little bit less clear to be honest here you want to basically go ahead and say the state of this component is an object and inside of that object we have a count which has initial value of zero now if i wanted another one i would go ahead and say age and in this case i could say age is 26 and that's how we would do it in this case now notice immediately that the benefit of doing in a functional component manner is that we actually get a setter for each piece of uh for each piece of state which is inside of the component whereas here we don't get a setter for each okay so something to know now we don't have the set count functions inside of a class-based component so here i'm going to go ahead and remove these as such in order to update the component inside of a class-based component i need to go ahead and say this dot set state now it's this because if you've ever done any class-based programming it's going to be referring to this instance of the class because class-based programming follows the object-orientated approach whereby we would have an instance of the class that we're defining so here we say this dot set state and what we then do is we pass in an object and here what we can do is we can say count right now the count here we can say is this dot state dot count plus one for the increment so notice how previously i actually was able to just directly access the account because we just got the variable itself but in a class we need to say this instance of the class so this object that we're referring to access the state and then go into the account and increment it so you see there is a difference there and the code is a little bit actually quite more complicated as opposed to the functional component and here what i can do is i can copy this go to the decrement and do minus one okay save it and what i'm going to now do is rather than using our app i'm going to go to index.js and i'm going to make it poor so i'm going to say import the app but instead import it from our app class okay and now we should be pulling it from this one now it says a few things it says count is not defined increment is not defined and decrement is not defined the reason why this is happening is because inside of a class-based component we need to now have the this keyword so we now need to say for the count we need to say this dot state dot count to access the cam inside of the state and also for the class functions we need to say this dot decrement and this dot increment save it and now you can see it's compared successfully so going back now if we go ahead we get the exact same functionality and as we expect if we refresh it resets to zero now as you can imagine out of the two options just from a glance which one seems more simple from this comparison it's very clear that the functional component is the preferred choice when we're writing a new component however as i mentioned previously it's going to be likely that the case is that the code base that you're going to be working on is class based in which case translating this over to a functional component is actually very very important right and if we were going to go ahead and do that right now i will show you how i would do it so here i would go ahead and change this to be const i would remove the class i would remove the extends component and then i would go ahead and make this an arrow function so you can do this or instead of this you can go ahead and make a function in which case you just need to get rid of this and you get rid of the arrow right so you can do that as well now we don't need the constructor but instead we need to replace this piece of state so remember we used a use state hook previously so now i can go ahead and say const and we need a count and remember the standard is to say set count we're going to say use state and the initial value is zero which means i can get rid of this entire block okay awesome now we have this dot set state so remember in a functional component we have the setters so here i can say set count and i don't no longer need to do this so here we had previously this dot state dot count now i can just say count plus one so i can get rid of this piece of code done and the same goes for this one so i can say set count count minus one so you see the coding is actually a lot more simple in a functional component awesome now what i need to do is these need to be const because these are now arrow functions which are variables inside of our functional component because they're simply just normal functions and then what we do we need to do is delete the render block because in a functional component we can simply return now we don't need the this dot state because we can directly access the count so we can get rid of that and then here we can actually go ahead and get rid of this dot decrement and this dot increment we can hit save and the final piece of the puzzle is we now need to export this so we know this export default app class as such okay now once we've done that you can see everything is still working and just to prove that this is still the correct class that we're using inside of index.js we are pulling it from app class which is this one over here and it is still doing the exact same functionality but instead it's a functional component now here's something to remember when you're dealing with class-based components whenever we update the state it can be asynchronous now this means that we could be updating the state in several different places on the page at one point in time so this dot state dot count could be triggered and it could be out of sync with another action on the page so the way that we deal with this is whenever we call this dot set state what we have to do is go ahead and we actually get an argument here and we get the previous state as an argument so here we can say previous state right and instead of this dot state now what we can now do is we can say the previous state dot count okay and then here what we simply need to do is wrap these in parentheses okay because now we're returning an object if i go ahead and click increment we can now see it still works as such and the decrement still works in the previous matter okay now what we want to do for this one is this will ensure that at the moment we hit the increment and if we decided to set the state we are going to use the exact previous state value at that point in time to manipulate the count inside of state so here i'm going to do the same thing i'm going to say the previous state and i'm doing a return so i need to put parentheses around here and this would have the previous state and this would now say the previous state dot count okay and if i go ahead refresh this and do it there we go everything is still working as expected and now regardless of if we call this several times in different places at the same point in time it will update in the correct appropriate way with that said guys that is our introduction into state for react is a very important principle i would highly recommend that you go over to the react docs and now give this a read so we're going to go to the react docs over here simply go to get started go down to main concepts state and life cycle and give this page a read we will be covering the life cycle in a upcoming lesson but next we're going to be talking about props and why props are so important inside of react so get excited i will see all of you in that lesson peace [Music] you
Info
Channel: Sonny Sangha
Views: 15,498
Rating: 4.9491739 out of 5
Keywords: react, developer, reactjs, html, css, js, javascript, papa, papareact, papa-react, tutorial, frontend, webdev, dev, clone, backend, fullstack, motivation, reactnative, react-native, redux, typescript
Id: kkuq0gTGRFQ
Channel Id: undefined
Length: 19min 28sec (1168 seconds)
Published: Sun Aug 29 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.