In this post, we will see how to resolve React two different useState change at the same time
Question:
This is a simple form table with two states – one (employees
) is to keep track of the updated form value, and the other (records
) should have saved the form values only when the add/save button is clicked.The issue is that whenever
handleChange
is called, it starts to update both the states, which is very weird since setRecords
is not called in there.what am I doing wrong that causes the two states to change together?
I suspect that it has something to do with how I initialized the two states here. What is the correct way to do it then?

Best Answer:
Right here you are mutating the original object:You should instead create a new employee so as not to mutate the original:
{...emp}
only duplicates the object one level deep. If one of the object’s properties was another object, the spread operator would not duplicate the nested object. Sometimes it’s better to duplicate your objects before passing them as the default value to useState
. Generally you’d use a class constructor or a function for that. Something to keep in mind.If you have better answer, please add a comment about this, thank you!
Source: Stackoverflow.com