Skip to content

Using useState with an object: how to update

FULL-STACK WEB DEVELOPMENT BOOTCAMP

2024 COHORT SIGNUPS END TOMORROW

When a state variable defined with useState is an object with properties you add / update, itโ€™s somewhat confusing how to update it.

You canโ€™t just update the object, or the component wonโ€™t rerender.

A pattern I found involves creating a temporary object with one property, and use object destructuring to create a new object from the existing 2 objects:

const [quizAnswers, setQuizAnswers] = useState({})

...

const updatedValue = {}
updatedValue[quizEntryIndex] = answerIndex
setQuizAnswers({
  ...quizAnswers,
  ...updatedValue
})

The same technique can be used to remove a property:

const copyOfObject = { ...quizAnswers }
delete copyOfObject['propertyToRemove']

setQuizAnswers({
  ...copyOfObject
})
โ†’ Get my React Beginner's Handbook
โ†’ Read my full React Tutorial
  • Learn modern web development in my BOOTCAMP (SIGNUP END TOMORROW FEB 20, 2024)
  • THE VALLEY OF CODE (+ PRO), your web development manual
  • I wrote 15+ coding BOOKS, all available in THE VALLEY OF CODE PRO
  • Indie solopreneur internet business masterclass SOLO LAB (summer 2024)