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!!
After running the above code, we get the output as follows:
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:
Here we get our actual output!!
Happy coding!!
-Jayant Khandelwal
Top comments (5)
useReducer is better for this
Yes Ivan, agreed!
For Forms there is also use-hook-form I use it everywhere it is very clean and easy to use.
Very nicely done. I'll just add when the object you're managing becomes too complex, useReducer can be utilised!
Yes cadell, agreed with you!