React Hooks Tutorial – 2 – useState Hook
- December 25, 2023
- Posted by: MainInstructor
- Category: BASIC JavaScript React
![*](https://i0.wp.com/allprowebdesigns.com/wp-content/uploads/2023/12/1703502257_maxresdefault.jpg?resize=840%2C430&ssl=1)
Video Title: React Hooks Tutorial – 2 – useState Hook
All right in this video let’s start with the very first hook which is the state hook up until now if you started writing a functional component and then ran into a situation where you needed to add state you would have to convert the component to a class component that is
Simply because state could only be used in class components that is about to change because the state hook which we will learn in this video allows us to use state within functional components to understand how the state hook works we are going to take a look at a simple
Counter example and for the benefit of those who are learning hooks with the knowledge of class components I will start of the video by implementing the counter with a class component and then implement the same with functional components and the state hook if you are new to react and starting off with just
Hooks you don’t have to worry about the class component implementation alright to get us started I have already created a project using create react app the first thing I’m going to do is in app dot chess get rid of the header and the logo import now we can get started with the code
First up a counter using a class component in the source folder I’m going to create another folder called components within the folder I’m going to create a file called class counter dot j/s within this file we implement the class-based counter component I’m going to use the
Snippet RC e to create a class component and get rid of the named export next create a state variable called count and initialize it to zero after that create a method called increment count which increments the count value by one so this dot set state count is
Going to be this dot state dot count plus one in the render function for the JSX add a button on click of that button call the increment count method and for the inner text we display the count value count is going to be this dot state dot count
Finally in the app component include the class counter component if you now save the files and take a look at the browser we should have a button with count initialized to zero I click on the button and the count value increments pretty straightforward what I want you
To keep in mind the three steps which are necessary to implement this counter the first step is to create a component and we have used a class component the second step is to create a state variable initialized to 0 the last step is to create a method that
Is capable of setting this state value with these three steps in mind let’s see how to implement the same counter with a functional component and the state hook within the components folder I’m going to create a new file called hook counter yes and within the file I’m going to use the
Snippet RFC II to create a functional component as part of the JSX I’m going to add a button the button will have an onclick handler and also the count as the inner text we will fill them in shortly now back to our three steps necessary to implement the counter first
Step is to create a component we have already done that but this time we have created a functional component step two we need a state property initialized to zero and step three we need a method capable of setting that state property value since we are working with a functional
Component we cannot use state like we did before we need a different way to implement steps two and three and that is where the use State hook comes into picture if you remember a hook is just a special function that lets you hook into react features so you state is a hook
That lets you add react state to functional components let’s take a look at the code the begin by importing it from react so use state which is unnamed import now the question is how do we use it in our component well hooks are just functions so we simply call them use
State this hook or function accepts an argument which is the initial value of the state property and returns the current value of the state property and a method that is capable of updating that state property and that sounds more complicated than it is so let me show
You the code so you state accepts the initial value of the state variable which is 0 and returns a pair of values current value of the state variable which we are going to call as count and a method that can update the state variable which we are going to call as
Set count this syntax right here is called array restructuring which is a feature in es6 if you’re unaware of what is added destructuring pause the video quickly read up on the topic and then resume shouldn’t take you more than five minutes now the names count and set count are chosen so that
It makes sense when you read the code but you can name them anything you want to could be number and set number or even completely random variable names like subscribe or enable notifications alright with this we basically have our step two and step three implemented a state variable count initialized to zero
And a method set count capable of changing the count variable we can now use these variables in the JSX the innertext count is what we want to render and on click we call set count passing in the new count value and what is the new count value current count plus one and
Since this becomes a function call that’s converted into an arrow function and that is pretty much it we have implemented all the three steps we have a functional component a state variable initialized to zero and we also have a method that is capable of updating the state variable back in app component
Let’s comment out class counter and include the hook counter if you now save the files and take a look at the browser the counter works exactly like before so this is a basic example of how to use the state hook in react import you state call it passing in a default value
Assign the return pair of values to variables using a DD structuring and use them in the render function the variable count will always contain the current state value and set count will accept an argument and set count value to that argument and how does this work with our
Counter example well the very first time the component renders a state variable is created and initialized with the default value of 0 the default value is never used on re-renders when you click on the button the set count method is called which will add one to the current
Count value on first click count is incremented to one from zero after that the set count method will cost the component to rerender after the rerender count will contain a value of 1 which is then displayed as part of the inner text in the browser now if you’re wondering
Why we would want to use this as opposed to class component and this dot state we already talked about that in the previous video now there are two important rules that you have to follow when using hooks and I just want to mention it here so that you’re not going
To try writing code in a way it isn’t supposed to be the is that only called hooks at the top level use hooks at the top level of your react function and don’t call hooks inside loops conditions or nested functions the second rule is only called hooks from react functions make sure you
Call them within react functional components and not just any regular JavaScript function though these rules are crucial to how hooks work so accept these rules for now we’ll talk more about why we need to follow them later on in the series well with that we wind up our introduction and the first
Example on the state hook let’s take a look at the next example in the next video thank you guys for watching don’t forget to subscribe I’ll see you guys in the next one
-
Sale!
Wireless WIFI Repeater Extender Amplifier Booster 300Mbps
$29.99$14.99 Add to cartWireless WIFI Repeater Extender Amplifier Booster 300Mbps
Categories: Electronics, Wi-Fi Router, Wireless Wi-Fi Extender Tags: 300Mbps, 802.11N, Amplifier, Booster, Extender, mobile wi-fi booster, Remote, WIFI, Wireless, Wireless WIFI, Wireless WIFI Repeater, Wireless WIFI Repeater Extender, Wireless WIFI Repeater Extender Amplifier, Wireless WIFI Repeater Extender Amplifier Booster, Wireless WIFI Repeater Extender Amplifier Booster 300Mbps$29.99$14.99 -
Sale!
Full RGB Light Design Gaming Headset Headphones with Mic
$24.99$14.99 Add to cartFull RGB Light Design Gaming Headset Headphones with Mic
Categories: Electronics, Gaming, Gaming Headsets Tags: Design, Full, Full RGB Light Design Gaming Headset, Full RGB Light Design Gaming Headset Headphones, Full RGB Light Design Gaming Headset Headphones with Mic, Gamer, Gaming, Gaming Headset Headphones, gaming headset wireless, Headphone, Headphones, Headset, Light, Mic, Package, RGB$24.99$14.99 -
Sale!
Wireless BlueTooth Multi-Device Keyboard Mouse Combo
$39.99$19.99 Add to cartWireless BlueTooth Multi-Device Keyboard Mouse Combo
Categories: Electronics, Gaming, Gaming Keyboards, Keyboard Mouse Combos Tags: Combo, Keyboard, keyboard mouse combos, Mouse, MultiDevice, Set, WireKeyboard Mouse Combo, Wireless, Wireless BlueTooth Keyboard Mouse Combo, Wireless BlueTooth Keyboard Mouse Combos, Wireless BlueTooth Multi-Device Keyboard Mouse Combo, Wireless BlueTooth Multi-Device Keyboard Mouse Combos$39.99$19.99 -
Sale!
High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
$199.99$139.99 Add to cartHigh Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
Categories: Gaming, Gaming Chairs Tags: Adjustable, Chair, computer chairs, Desk, Executive, Gaming, Girl, Headrest, High, High Back Leather Executive Adjustable Swivel Gaming Chair, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar, High Back Leather Executive Adjustable Swivel Gaming Chairs, Leather, Lumbar, Office, Racing, Swivel$199.99$139.99 -
Sale!
Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
$29.99$19.99 Select optionsProfessional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
SKU: N/A Categories: Electronics, Gaming, Gaming Headsets Tags: Cancelling, Gaming, Gaming Headphones with Noise Cancelling Microphone, gaming headset, Headphones, Headset, LED, Light, Mic, Microphone, Noise, Professional, Professional LED Light Wired Gaming Headphones, Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone, Wired, Wired Gaming Headphones, Wired Gaming Headphones with Noise Cancelling Microphone$29.99$19.99 -
Sale!
Gaming Desk with LED Lights USB Power Outlets and Charging Ports
$349.99$249.99 Select optionsGaming Desk with LED Lights USB Power Outlets and Charging Ports
SKU: N/A Categories: Computer Desk, Gaming, Gaming Desk Tags: and Charging Ports, Charging, Desk, Desks, Gaming, gaming desk with led lights, Gaming Desks with LED Lights, Home, LED, Lights, Monitor, Office, Outlets, Port, Power, Room, Stand, USB, USB Power Outlets, White, Workstation$349.99$249.99 -
Sale!
Wired Mixed Backlit Anti-Ghosting Gaming Keyboard
$99.99$79.99 Add to cartWired Mixed Backlit Anti-Ghosting Gaming Keyboard
Categories: Electronics, Gaming, Gaming Keyboards Tags: Antighosting, Backlit, Blue, brown, Gaming, Gaming Keyboard, gaming keyboards, gaming keyboards and mouse, Keyboard, Laptop, Switch, Wired, Wired Mixed Backlit Anti-Ghosting Gaming Keyboard, Wired Mixed Backlit Anti-Ghosting Gaming Keyboards, Wired Mixed Backlit Gaming Keyboard$99.99$79.99 -
Sale!
Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
$119.99$59.99 Add to cartWireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
Categories: Electronics, Gaming, Gaming Headsets Tags: 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, ANC, Audio, Bluetooth, Cancellation, Ear, Earphone, gaming headset, Headphones, Headset, Hi-Res Over the Ear Headphones Headset, HiRes, Noise, Wireless, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Headphones, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headsets$119.99$59.99 -
Sale!
Wired Sports Gaming Headset Earbuds with Microphone
$19.99$9.99 Select optionsWired Sports Gaming Headset Earbuds with Microphone
SKU: N/A Categories: Gaming, Gaming Headsets Tags: Accessories, Earbud, Earphone, Earphones, Gaming, gaming headset with microphone, Headphones, Headset, IOS, Microphone, Sports, Wired, Wired Sports Gaming Headset Earbuds, Wired Sports Gaming Headset Earbuds with Microphone, Wired Sports Headset Earbuds$19.99$9.99 -
Sale!
150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
$49.99$29.99 Add to cart150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
Categories: Charging Stations, Electronics Tags: 150W, 150W Charging Station, 150W Universal Multi USB Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Stations, 150W Universal Multi USB MAX Charging Station, 16 Port MAX Charging Station, 3.5A, Charger, Charging, Fast, laptop charging stations, Max, Multi, Port, Stand, Station, Universal, USB$49.99$29.99
You said before that whenever you have to update state based on the previous one we need to pass a function as argument to setState
instead of passing in an object. So why you don't stick to that in the class component example? 😖
6:42–6:53 Oh I see what you did there. Considering the nonchalant tone it is ridiculously brilliant 😄
You are a perfect teacher. Slow pace, comparison, and almost gets every point that should be highlighted
in the class component, why didn't you use the callback function which receives previousState as argument?
I am enjoying it
Thanks myannn <3
Hooks learning started
6:53 I see what you did there, you sneaky dog
Best tutorial on react hooks.
Thanks
Being primarily a Java developer (Spring Boot, etc) I was leery of dismissing class components in favor of functional ones. Now I finally understand why this is a better approach. The various hooks, including useState, make this a much easier way to properly organize and configure components. thanks.
omg this is much more simpler than classes!!!
This is the best React course so far
{2022-10-14}
Thanks
Thanks a lot for explaining concepts like hook in much simpler way
Awesome
is it possible to use onClick={()=>this.setState({count:this.state.count+1})} in class component???
class way: class component, state variable, setState in an arrow function
hooks way: func component, useState with array restructuring – variable & method, call that method from arrow function
here array destructuring is different from object destructuring as the useState( ) returns a pair
Best teacher fr
when to use inline function in onClick <button onClick={()=> setCount(count+1)}>
vs
just a function call like <button onClick= {setCount(count+1}}>
how extension are you using for the shortcuts??
I was trying to find JSX shortcut extensions but none of them had much shortcut
need a playlist in functional components please!
I am new to react and have development work in a week, this series is a booster dose !! Thanks for the amazing content.
Why we are giving arrow function in onclick
well explained! even for a newbie its easy to digest, disintegrating every thing in steps, telling the names, purpose and functions of terms, and giving a quick review of things once they are finished, your this video is a must watch for every beginner
Thank you Vishvas!
super explanation