React setState() update nested object

There are two sides to the story of updating nested state objects in React.

The short answer

The easiest way to update a nested object stored in the React state is to create a shallow copy and use the spread operator.

Updating a 1-level deep object

Let's say we have the below object in a React state variable:

const [cat, setCat] = useState({
    name:'Achilles the 😸',
    origin: 'Greece 🇬🇷',
    owner: {
        name: "Daniel", 
        age: 38
    }
})

To update a 1-level deep property, eq owner.name, we can do:

setCat(prevCat => ({
    ...prevCat,
    owner: {
        ...prevCat.owner,
        name: "Daniel the owner of Achilles"
    }
}))

Updating a 2-levels deep object

If we have a more complex nested object, like the one below:

const [cat, setCat] = useState({
    name:'Achilles the 😸',
    origin: 'Greece 🇬🇷',
    owner: {
        name: "Daniel", 
        age: 38,
        job: {
            title: "Software Developer", 
            location: "At home"
        }
    }
})

We can use the same approach, but the mind the extra deep of the state object:

setCat(prevCat => ({
    ...prevCat,
    owner: {
        ...prevCat.owner,
        job : {
            ...prevCat.owner.job,
            title: 'Cat slave'
        }
    }
}))

I've made this example on Github. And you can see it live here.

React state update nested object

For 3 nesting levels and above keep in mind to spread each level of the nested object.

The long answer

The long answer is ... don't use setState() to update nested objects!

The nested state is a wrong design pattern, given that React embraces the concept of state immutability.

We can try to flatten the state. For example:

// before 
const [cat, setCat] = useState({
    name:'Achilles the 😸',
    owner: {
        name: "Daniel", 
    }
})

// after 
const [cat, setCat] = useState({
    name:'Achilles the 😸',
    ownerName: "Daniel"
})

You can flatten your state by hand or use a third-party library similar to Normalirz.

Another solution is to use immutable helpers such as immutability-helper or immer.

📖 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

📖 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *

Home Screencasts Best of Newsletter Search X

📖 50 Javascript, React and NextJs Projects

Hi friend! Before you go, just wanted to let you know about the 50 Javascript, React and NextJs Projects FREE ebook.

One of the best ways to learn is by doing the work. Choose from 8 project categories and get started right away:

  • Business & Real-World
  • Games & Puzzles
  • Fun & Interesting
  • Tools & Libraries
  • Personal & Portfolio
  • Project Add-Ons
  • Productivity
  • Clones

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects complete with project briefs and wireframes!

Keep building and level up! Get all projects as an ebook right to your inbox!

X