šŸ“• Build AI Agents using LangGraph.js is now out!

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.

šŸ“– Build a full trivia game app with LangChain

Learn by doing with this FREE ebook! This 35-page guide walks you through every step of building your first fully functional AI-powered app using JavaScript and LangChain.js

šŸ“– Build a full trivia game app with LangChain

Learn by doing with this FREE ebook! This 35-page guide walks you through every step of building your first fully functional AI-powered app using JavaScript and LangChain.js


Leave a Reply

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