React Hooks Tutorial – 4 – useState with object
![*](https://i0.wp.com/allprowebdesigns.com/wp-content/uploads/2023/12/1703531159_maxresdefault.jpg?resize=840%2C430&ssl=1)
Video Title: React Hooks Tutorial – 4 – useState with object
Alright guys in this video we are going to take a look at another example which makes use of the state hook we will be discussing about using an object as a state variable with the you state hook to get started I’m going to create a new
File called hook counter 3 dot J s within the file I’m going to use the snippet RFC II to create a functional component for the next step I’m going to include the US state hook so import you state from react and within the component Const name comma set name is
Going to be equal to you state this time though the default value will be an object the object will contain first-name and lastname initialize to an empty string so this is an important point to keep in mind a state variable can be a string a number boolean an
Object or even an array you can use any of those types based on your requirement alright so we now have a state variable called mean which is an object and a setter function set name to update the corresponding state variable next let’s define the render function you basically
Want to have two input fields one for first-name and one for last name so let’s add a form tag an input element type is equal to text this is for the first name and a second one for the last name below the input fields we simply
Display the first name and the last name you can add an h2 tag your first name is name dot first name and similarly your last name is name dot last name next let’s handle the value attribute and the on change event on the two input fields for first name value is going to
Be equal to name dot first name and on change that is whenever the user starts typing in something we want to set the first name property so event our function call set name which is the setter function for the name state variable and what do we want to set we
Want to set first name equal to event dot target dot value and let’s do the same for last name I’m going to copy this input tag and replace the second one I’m going to change value to name dot last name and in the set name function last name is going to be equal
To e dot target dot value so basically whenever the first input field value changes we update the first name property and when the second input field value changes we update the last name property let’s test this out meant to include hook counter three in ABA’s save
The files and head to the browser and type in the first input field which was and you can see that the first name is now displayed I start typing in the second input field and you can see that we have a problem the last name is displayed fine but then
The first name is now empty if I start typing in the first input field we have the first name but the last name is now empty so there is something happening with the state variable to visualize that I’m going to go back to B as code and add another line in the JSX
I’m going to display the name state variable so it’s two json dot stringify name if you now go back to the browser you can see that by default we have both first-name and lastname set to empty strings now when I start typing in the first name the last name property is
Removed from the state variable if I start typing in the last name the first name property disappears from the state variable the reason this happens is because you state does not automatically merge and update the object this is a key difference to set state which you come across in class components said
State will merge the state whereas the use state hook set of function will not merge the state you have to do it manually it’s not difficult though because we can use the spread operator to handle the manual merge so back in vs code on change and the arrow function we
First spread name and then set the appropriate property spread the name and then overwrite last name how do you read this is hey copy every property in the name object and then just overwrite the first name field with a different value similarly for last name just make a
Replica of the name object and then only up the last name property to the new value the spread operator which is a feature of es6 is a very common operator in use now if you are new to this do spend a few minutes to understand the spread
Operator and then resume the video so if you now save the file and go back to the browser type in the first name the first name is updated but you can see that the last name property is preserved type in the last name the first name is as it is
And the last name is updated with the new value so this is the third example I wanted to discuss to highlight one key point the setter function provided by the you state hook does not automatically merge and update objects you have to manually merge it yourself
And then pass the value to the setter function now we have a similar scenario when updating arrays so let’s quickly take a look at that example in the next video thank you guys for watching don’t forget subscribe and click on the bell icon to enable notifications
-
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
THANK YOU
When setting values for object from within loop for useState it behaves correctly compared to when we use a primitive like string or number. Why?
Just lovely
I needed this refresher! Thanks!!!
Love the way you teach. Very clear and you even show WHY we have to do something instead of just telling us to do it a particular way. Thank you!!
at 2:48 you said equal instead colon…give some attention bro..
¿Cuál es el atajo para separar los componenetes de la etiqueta en el minuto 2:53?
What i learned from EP04
1. passing object as a parameter in useState hooks
2. hooks does not update object so we have to do it manually
3. use of … in hooks to manipulate object here in our case we just copy that object and update some property of that object:)
Thankssss Youuuuuuu!
You deserve more, i swear if you come and pay visit to south Sudan one day, I will give you big cow
Thank You So Much Vishwass Sir 😌😌😌
import React, { useState } from 'react'
function UseStateObject() {
const [data, setData] = useState({ name: "TejasPhatangare", age: 21 })
const namehandler = (e) => {
setData({ …data, name: e.target.value })
}
const agehandler = (e) => {
setData({ …data, age: e.target.value })
}
return (
<>
<input type='text' value={data.name} onChange={namehandler} />
<input type='text' value={data.age} onChange={agehandler} />
<h2>Name : {data.name}</h2>
<h2>Age : {data.age}</h2>
</>
)
}
Watched thanks
Takeaway: when using an object as your state, you have to merge the old object and the new object when setting state if you’re replacing the old object with a new object.
If using the version of setState that provides the old value that shouldn’t require merging so always use the setState that gives you oldValue
Excelente ! Muito Bem Explicado ! ! Parabéns pelos vídeos ! ! !
Thank you for sharing your knowledge
Very nice explanation
great video. as someone that is watching alot of tutorials that bring up different areas of react i appreciate that you explain those areas such as the spread. revisiting these topics as someone learning makes it easier to understand after hearing it again. appreciate your videos! thank you!
You are a lifesaver! Thank you very much, you earned a sub.
Can you add button append value to object in this example
This is really a bad example guys. Don't follow this. The onChange function should be like this
onChange={e => setName(prevName => {…prevName, firstName: e.target.value})
Is it better to have an object that handles both input fields or two state variables for each input field? Can you explain why one is better than the other?
The best tutorials i throught
{2022-10-14}
Thanks bro, I have been facing this error for two days.
what would I do if I want to add something rather than modify one value?
ok ok ,,,, So this is the real React.js about which I was not knowing anything…… Best tutorial series ever ✅✅⭐⭐
solved my issues and you seem to point out important concepts. I will subscribe for that. Appreciate your time and effort
Thank you so much❤️
thank you sir 🙂
Love your work! What extension are you using for autocomplete?
Hello Sir!
I have problem in useState:
import React, {useState} from 'react'
function App(){
var [data, dataUpdate]=useState(0);
function change(){
dataUpdate(data+1);
}
return (
<div>
<h1>{data}</h1>
<button onClick={()=>change()}>Click Here</button>
</div>
)
}
export default App
Whenever i used useState it shows me the blank page after execution
Thank you 👍🏻
Alhumdulillah
Thank you very much brother
thanks you are great!
Thank you, exactly what I was looking for.
there is a an arry of characters in app.js and using another compnent how can we iterate these characters with button click and useState
i could write up to some extent but i am not getting required input
can you help me
onChange={(e) =>
setName((prev) =>
Object.assign({ …prev, firstName: e.target.value })
)
}
For updating with previous object.
1. state variable – can be number, string, bool, object { }, array [ ]
if object – then -> name.firstName
2. useState – will not update the state variable. whereas in class: setState will merge the state variable.
can overcome by using spread operator.
JSON.stringify()
i never understood why in every react tutorial we havee to update the value , it works fine in my case without doing that, whever i type anything it appears on my screen , it renders
great ! Saved my time, even if I have a lil bit more experience than amateur, this simple things sometimes disappears from head 😀 Thank you !
Thank's for the explanation, helped me a lot. =D
How to change for button tag not input
because of this man i still have a job lol <3
it's video really Good…