Nested State Objects in React Hooks

Dwayne
2 min readDec 16, 2020

No doubt, there is decent amount of material covering the use of objects in useState(for example) in React. I happened to find a particular use case “just” unique enough for me to try and give a little more perspective on how to use objects that might be a bit more deeply nested in React.

Let’s say you’re making a movie app, and you need to give your viewers the add-movie option. You’ll probably have an example akin to the one down below.

Example:

In this example, I’ve provided only one input tag for only one of the values in our state object. A real life example is of course much beefier. I removed all the fat in order to narrow in on the solution.

Often, the difficult part about nested state objects in React is knowing where to use the spread operator {…} for objects and/or arrays. If you don’t place the proper spread operator where it should go, the data you place into state will only persist for one of the inputs within the Comment section or even worse immediately drop the Comment section and create a new value.

Additionally, the comment section inside of the input tag will either end up preserving information for the moniker or the body input(not both), depending on what section was last used in updating the state.

Here we see an example where on line 24, you can update the input value of moniker without affecting the body input value.

I could spend all day showing you what doesn’t work or what may seem like it could work but I wrote this article for the sake of bypassing those issues. Hopefully this example gives you the solution or leads you to the right path.

Have fun coding!

--

--

Dwayne
0 Followers

Graduate of General Assembly, living in New York, and coding everyday