šŸ“™ Understanding Neuronal Networks presale is now open - 20% off discount!

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.

šŸ“– Neural Networks from Scratch - Presale

I'm writing a book about the timeless foundational concepts of neural networks for JavaScript developers. Go from if-else to weights and biases by building tiny AI models from scratch!

šŸ“– Neural Networks from Scratch - Presale

I'm writing a book about the timeless foundational concepts of neural networks for JavaScript developers. Go from if-else to weights and biases by building tiny AI models from scratch!


Leave a Reply

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