How to update nested state properties in React?

Posted by Ramesh Singh | Updated on

Want to update nested state properties in React? In order to setState for a nested object you can follow the below approach as I think setState doesn’t handle nested updates.

The idea is to create a dummy object perform operations on it and then replace the component’s state with the updated object. Now, the spread operator creates only one level nested copy of the object. If your state is highly nested like:

You could setState using spread operator at each level like:

However the above syntax get every ugly as the state becomes more and more nested and hence I recommend you to use immutability-helper package to update the state.


If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.

Related Questions & Answers