Paul Hsueh
3 min readJul 30, 2021

--

Handling Nested States with React Hooks

Photo by James Harrison on Unsplash

As my final blog while attending bootcamp, I decided to share my understanding of handling nested states with React Hooks. This issue can likely pose a challenge for any up and coming software developer. All the credit for my understanding goes to my coach. I will dive right into the issue and followed up with some commentary, so let’s get to it.

JSON response that will update state

My goal was to use the above JSON response to update ‘categories’ (line 19) below in my application state. The component where the JSON response was coming from was nested two levels deep in my component tree — a callback function definition was passed down as props to be invoked so App.js can receive the response.

State to updated, line 13 to line 21

It’s important to bear in mind that state gets completed replaced in React Hooks when making updates. So a deep understanding of array iteration is extremely handy.

Solution

The solution that I learned was to handle the response I was getting called ‘goal’ (line 97) is described below.

Solution that I learned, line 97 to line 125

1. Declare a helper function that can be invoked within the child component — the function called ‘replaceCategoryInState’ at the top level component (App.js) is being passed down as props and is being invoked by the response called ‘goal’ (line 97)

2. Use the ‘.find’ method to find the new object to add to the ‘goals’ array insde the JSON response — the structure of the array represented by ‘goal’ (line 97) is what exactly what you see in the first image of the JSON response

3. Add the object to the existing goals array that is nested inside the category array (line 102) with the spread operator

4. Declare a helper function (line 112) that will set the new state — using the ‘.map’ method to return the updated array that includes the nested array of ‘goal’ objects you wish to update and then set the new state (line 121)

5. Lastly, invoke the helper function (line 109) — and there you have it!

Reflection

Upon reflection, coding has been a process of understanding how information is moving throughout the program. Dealing with nested state is an exercise in that understanding. Nested data will be present in many APIs and datasets and becoming proficient in extracted information from them is of great use. In the case of updating nested states, I would image there could be better tools to use but for now this way worked! Hopefully, this gives everyone a guide to update nested states with Hooks. Thanks for reading!

--

--