DEV Community

Jayant Khandelwal
Jayant Khandelwal

Posted on • Updated on

useState with objects (what the hack!!)

Popular Questions

1.)How do useState behaves while taking the initial state as an object?

2.)Why do we make use of spread operator while dealing with the objects as the initial state?

Here's the solution!!

useState with object eg

After running the above code, we get the output as follows:

a.)
useState with object opt

b.)
useState with object opt

We can clearly see that while entering the first name, the last name gets disappear from the Heading and vice versa.

But why is it happening? why are not we able to see both the first name and last name simultaneously?

Reason:
This is happening because useState does not automatically merge and update the object (contrary to setState while using class-based components) i.e. useState does not merge the state automatically.
We have to do it manually with the help of spread operator.

Solution:

Alt Text

Output:
Alt Text

Here we get our actual output!!

Happy coding!!
-Jayant Khandelwal

Buy Me A Coffee

Top comments (5)

Collapse
 
ivan_jrmc profile image
Ivan Jeremic

useReducer is better for this

Collapse
 
jackent2b profile image
Jayant Khandelwal

Yes Ivan, agreed!

Collapse
 
ivan_jrmc profile image
Ivan Jeremic

For Forms there is also use-hook-form I use it everywhere it is very clean and easy to use.

Collapse
 
cadellsinghh_25 profile image
Cadell

Very nicely done. I'll just add when the object you're managing becomes too complex, useReducer can be utilised!

Collapse
 
jackent2b profile image
Jayant Khandelwal

Yes cadell, agreed with you!