2025

Here's an update showing a live code demo so you can verify the results in your own browser -

function App(props) {
  const [state, setState] = React.useState(props.initialState)
  function updateObj(index, key, value) {
    setState(s => [
      ...s.slice(0, index),
      { ...s[index], [key]: value },
      ...s.slice(index + 1),
    ])
  }
  return <div>
    {state.map((o, index) =>
      <div key={o.id}>
        <input value={o.foo} onChange={e => updateObj(index, "foo", e.target.value)} />
        <input value={o.bar} onChange={e => updateObj(index, "bar", e.target.value)} />
        <input value={o.qux} onChange={e => updateObj(index, "qux", e.target.value)} />
      </div>
    )}
    <pre>{JSON.stringify(state, null, 2)}</pre>
  </div>
}

ReactDOM.createRoot(document.querySelector("#app")).render(
  <App
    initialState={[
      { id: 1, foo: "a", bar: "b", qux: "c" },
      { id: 2, foo: "j", bar: "k", qux: "l" },
      { id: 3, foo: "x", bar: "y", qux: "z" },
    ]}
  />
)
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<div id="app"></div>

2020

Things have changed a lot since I wrote this, but leaving the original for posterity.

Your update function would look like this -

updateItem(id, itemAttributes) {
  var index = this.state.items.findIndex(x=> x.id === id);
  if (index === -1)
    // handle error
  else
    this.setState({
      items: [
         ...this.state.items.slice(0,index),
         Object.assign({}, this.state.items[index], itemAttributes),
         ...this.state.items.slice(index+1)
      ]
    });
}

And you use it like this -

this.updateItem(2, {someattr: 'a new value'});

Gross right?


You're going to have a big headache in general if you continue to build a complex application in this manner. I would recommend you look into redux or some other Flux implementation that is better suited for solving these problems.

Redux uses a concept of state reducers which each work on a specific slice of the state of your application. That way you don't have to manually dig through your entire state each time you want to affect a deep change.

The creator of Redux, Dan Abramov, has made two video courses available online for free. Dan is an excellent teacher and I felt comfortable with the Redux pattern after spending just one afternoon with it.

  • https://egghead.io/courses/getting-started-with-redux
  • https://egghead.io/courses/building-react-applications-with-idiomatic-redux
Answer from Mulan on Stack Overflow
🌐
React
react.dev › learn › updating-arrays-in-state
Updating Arrays in State – React
Just like with objects, when you want to update an array stored in state, you need to create a new one (or make a copy of an existing one), and then set state to use the new array.
Top answer
1 of 7
62

2025

Here's an update showing a live code demo so you can verify the results in your own browser -

function App(props) {
  const [state, setState] = React.useState(props.initialState)
  function updateObj(index, key, value) {
    setState(s => [
      ...s.slice(0, index),
      { ...s[index], [key]: value },
      ...s.slice(index + 1),
    ])
  }
  return <div>
    {state.map((o, index) =>
      <div key={o.id}>
        <input value={o.foo} onChange={e => updateObj(index, "foo", e.target.value)} />
        <input value={o.bar} onChange={e => updateObj(index, "bar", e.target.value)} />
        <input value={o.qux} onChange={e => updateObj(index, "qux", e.target.value)} />
      </div>
    )}
    <pre>{JSON.stringify(state, null, 2)}</pre>
  </div>
}

ReactDOM.createRoot(document.querySelector("#app")).render(
  <App
    initialState={[
      { id: 1, foo: "a", bar: "b", qux: "c" },
      { id: 2, foo: "j", bar: "k", qux: "l" },
      { id: 3, foo: "x", bar: "y", qux: "z" },
    ]}
  />
)
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<div id="app"></div>

2020

Things have changed a lot since I wrote this, but leaving the original for posterity.

Your update function would look like this -

updateItem(id, itemAttributes) {
  var index = this.state.items.findIndex(x=> x.id === id);
  if (index === -1)
    // handle error
  else
    this.setState({
      items: [
         ...this.state.items.slice(0,index),
         Object.assign({}, this.state.items[index], itemAttributes),
         ...this.state.items.slice(index+1)
      ]
    });
}

And you use it like this -

this.updateItem(2, {someattr: 'a new value'});

Gross right?


You're going to have a big headache in general if you continue to build a complex application in this manner. I would recommend you look into redux or some other Flux implementation that is better suited for solving these problems.

Redux uses a concept of state reducers which each work on a specific slice of the state of your application. That way you don't have to manually dig through your entire state each time you want to affect a deep change.

The creator of Redux, Dan Abramov, has made two video courses available online for free. Dan is an excellent teacher and I felt comfortable with the Redux pattern after spending just one afternoon with it.

  • https://egghead.io/courses/getting-started-with-redux
  • https://egghead.io/courses/building-react-applications-with-idiomatic-redux
2 of 7
10

If you were using functional components and the useState hook, you could easily use map, as long as you don't mind substituting the entire object

const [items, setItems] = useState ([
    {id: 1, someattr: "a string", anotherattr: ""},
    {id: 2, someattr: "another string", anotherattr: ""},
    {id: 3, someattr: "a string", anotherattr: ""},
])

setItems (
    items.map((item) => {
        return item.id === updatedItem.id? updatedItem: item;
    })
); 
Discussions

reactjs - SetState of an array of Objects in React - Stack Overflow
Ok, so I'm so frustrated finding the right solution so I'm posting the problem here. Giving an answer would help me a lot, coz I'm stuck! the state tree looks like this this.state = { item... More on stackoverflow.com
🌐 stackoverflow.com
Efficient way to add objects to state arrays?
It's ineffective no matter how you do it and obviously stresses GC a lot. But given the arrays are usually small, it's not that bad practically. It's kinda silly legacy way to track updates but that's how the library was built. If you have performance intensive tasks, they are better handled outside React. You can always sync the changes then to update views etc. More on reddit.com
🌐 r/reactjs
50
14
March 2, 2025
How to set state to an array of objects in react
I am working on a flash card react application. I have initialized my state as an array of objects (the user can only add up to 10 terms/definitions at a time so limited to 10) as follows: state =... More on stackoverflow.com
🌐 stackoverflow.com
How to change property of one object in an array of objects in React state?
I have an array of JavaScript objects that I holding in React State, and on a click, I change the property of one of the objects in the array. I got the following to work without mutating state, bu... More on stackoverflow.com
🌐 stackoverflow.com
People also ask

How do you update nested array of objects in React state?
When updating a nested array of objects, you need to create new instances of the arrays and objects at each nesting level to avoid direct mutation.
🌐
dhiwise.com
dhiwise.com › post › react-update-array-of-objects-in-state-a-developer-guide
Guide to React Update Array of Objects in State
How do you update an array of objects with another array of objects?
You can update an array of objects with another array by using methods like map, filter, or
🌐
dhiwise.com
dhiwise.com › post › react-update-array-of-objects-in-state-a-developer-guide
Guide to React Update Array of Objects in State
How do I update a state object in Reactjs?
To update a state object in React, use the setState function or useState hook to create a new object with the updated properties and set the state with the new object.
🌐
dhiwise.com
dhiwise.com › post › react-update-array-of-objects-in-state-a-developer-guide
Guide to React Update Array of Objects in State
🌐
Pluralsight
pluralsight.com › blog › guides
Manipulating Arrays and Objects in State with React | Online Courses, Learning Paths, and Certifications - Pluralsight
November 4, 2020 - With the introduction of hooks in React 16.8, functional components can now also handle state in a simplified way. The snippet below is the class-based <MyComponent/> written as a functional component. The useState hook is a function that takes in a default value as a parameter (which can be empty) and returns an array containing the state and a function to update it.
🌐
DEV Community
dev.to › andyrewlee › how-to-update-an-array-of-objects-in-react-state-3d
How to update an array of objects in React state - DEV Community
November 15, 2022 - const handleMarkComplete = (id) => { // 1. Find the todo with the provided id const currentTodoIndex = todos.findIndex((todo) => todo.id === id); // 2. Mark the todo as complete const updatedTodo = Object.assign({}, todos[currentTodoIndex]); ...
🌐
DhiWise
dhiwise.com › post › react-update-array-of-objects-in-state-a-developer-guide
Guide to React Update Array of Objects in State
June 7, 2024 - This pattern ensures that React knows about the state change and can re-render the component with the updated state. Updating an array of objects in the React state follows the same principle of immutability. Let's say you want to update the ...
🌐
YouTube
youtube.com › sam meech-ward
React State Array of Objects - YouTube
Learn how to use useState to keep track of arrays of objects in a react app.🔗Starter Code:https://github.com/Sam-Meech-Ward/react-state-arrays-jokes/tree/3c...
Published   September 22, 2022
Views   25K
Find elsewhere
🌐
DEV Community
dev.to › andyrewlee › cheat-sheet-for-updating-objects-and-arrays-in-react-state-48np
Cheat Sheet for Updating Objects and Arrays in React State - DEV Community
May 4, 2020 - This is a cheat sheet on how to do add, remove, and update items in an array or object within the context of managing React state.
🌐
Medium
medium.com › @hongsi140626 › programming-all-about-state-update-in-react-object-array-30e33bb89d38
All about state update in React(Object & Array) | by Jake Hong | Medium
April 17, 2023 - Just like with objects, when you want to update an array stored in state, you need to create a new one (or make a copy of an existing one), and then set state to use the new array.
🌐
DEV Community
dev.to › joelynn › react-hooks-working-with-state-arrays-2n2g
React hooks - working with state (array of objects) - DEV Community
August 6, 2021 - // import React and the useState hook import { useState } from "react"; import "./styles.css"; // component function function SimpleArrayOfObjectsComponent() { // set the initial state (an array with 1 object to start (this can be an empty object to start)) const [users, setUsers] = useState([ { id: 1, name: "Joe", type: "admin" } ]); export default SimpleArrayOfObjectsComponent;
🌐
Medium
medium.com › nahid-hasan › using-the-spread-syntax-in-react-js-to-set-state-array-of-object-c47c631f64b0
Using the Spread syntax in React Js to set state array of object | by Mirthful Nahid | NAHID HASAN | Medium
January 30, 2021 - Like This, the initial state. ... var carArray = [{ name : ‘Ford’ , price : 15000 }, { name : ‘toyota’ , price : 12000 } , { name : ‘Rover’ , price : 14000 }] ... But there was i little bit of problem in that . i was just pushing the object into the empty array at second index .
🌐
Robin Wieruch
robinwieruch.de › react-state-array-add-update-remove
How to manage React State with Arrays - Robin Wieruch
May 17, 2020 - The example shows you that it doesn’t make any difference for whether you are working with primitives or objects when using the previously applied JavaScript array methods. You would still use the array concat method to add an item, the array map method to update item(s), and the array filter method to remove an item. However, this time having an identifier for each item gives you more control over the array than having only indexes as before for the array manipulations. You have learned about different ways on how to manage React state with arrays.
🌐
GUVI
guvi.in › blog › programming languages › how to render an array of objects in react? [in 3 easy steps]
How to Render an Array of Objects in React? [in 3 easy steps]
October 21, 2025 - Within the function, you can access and render each object’s properties as and when needed, effectively iterating through and rendering them in your React component. To set an array of objects in the state of a React component, you can use the ‘useState’ hook.
Top answer
1 of 4
4

Your example is in fact mutating state here:

flashcard.show = !flashcard.show;

At this point, flashcard refers directly to an object in state, so altering one of its properties is a mutation.

You need a way to identify the objects in state so that you can extract one, clone it individually, and then insert it back into a cloned state array in its original position. Without changing any of your data, you could do this by passing the array position of the flashcard when you call toggleFlashcard.

{flashcards.map((flashcard: IFlashcard, i: number) => {
    return (
        <>
            <li><span onClick={() => toggleFlashcard(i)}>{flashcard.noun}</span>
                {flashcard.show && (
                    <>
                        : {flashcard.article}
                    </>
                )}
            </li>
        </>
    )
})}

Now the toggleFlashcard event handler should look something like this:

const toggleFlashcard = (i: number) => {
    const clonedCard = {...flashcards[i]};
    clonedCard.show = !clonedCard.show;
  
    const clonedState = [...flashcards];
    clonedState[i] = clonedCard;
  
    setFlashcards(clonedState);
}
2 of 4
1

If you don't want to mutate anything, please try this solution.

const toggleFlashcard = (flashcard: IFlashcard) => {
  const flashcardIndex = flashcards.findIndex(f => f === flashcard);
  const newFlashcards = [...flashcards];
  newFlashcards[flashcardIndex]= { ...flashcard, show: !flashcard.show };
  setFlashcards(newFlashcards);
};

And this is not related to the main topic but the key attribute is missing here.

{flashcards.map((flashcard: IFlashcard, index: number) => {
...
<li key={index}><span onClick={() => toggleFlashcard(flashcard)}>{flashcard.noun}</span>
                              

If you don't specify the key attribute, you will see React warnings.

🌐
Bobby Hadz
bobbyhadz.com › blog › react-typescript-usestate-array-of-objects
Type useState as Array or Object in React TypeScript | bobbyhadz
To type the useState hook as an array of objects in React, use the hook's generic. The state variable can be initialized to an empty array and will only accept objects of the specified type.
🌐
Reddit
reddit.com › r/webdev › an array of objects in react state?
r/webdev on Reddit: An array of objects in React state?
March 3, 2022 -

I want to make a swipable card components with user inputs. I have an array of objects with keys predefined so that I can capture the user input through fields. Say, for example, if I want to have 4 slides in that card with user inputs, how to handle the state in such a situation? how to correctly change the values of a specific item of the object without mutating other objects?

const object = {title: '', name: '', age: '', pic: ''};
const [card, setCard] = useState([object]);

This is how I defined the state.

I want to change the values of an object in the array by using the e.target.name and e.target.value. How to do it for 4 slides without affecting one another?

🌐
GeeksforGeeks
geeksforgeeks.org › how-to-render-an-array-of-objects-in-reactjs
How To Render An Array Of Objects In ReactJS? | GeeksforGeeks
April 12, 2025 - In this article, we’ll explore different ways ... setState in React is used to update the component state. Updating an object with setState involves modifying only specified properties of object without modifying the complete object.