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
63

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

How can I update state.item[1] in state using setState?
I'm creating an app where the user can design his own form. E.g. specify name of the field and details of which other columns that should be included. The component is available as a JSFiddle. My i... More on stackoverflow.com
๐ŸŒ stackoverflow.com
How do you update a value inside an array of objects with useState?
People already answered you here about how you use setState in your case. I would strongly suggest you to use useReducer instead of useState. It would allow you to have more complex operations tied to your state and thus, save you from writing too much code and increase readability. You could, for example, do this: dispatch({type: "update", obj: { id:3, newProperty: "hellowWorld" } }) or dispatch({type: "replace", obj: { id:3, ...properties }) Whenever your state gets too complex. Always consider using the useReducer hook . More on reddit.com
๐ŸŒ r/react
32
14
April 15, 2022
Whats the best way to update an object in an array in ReactJS?
If you have an array as part of your state, and that array contains objects, whats an easy way to update the state with a change to one of those objects? Example, modified from the tutorial on rea... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Is it possible to update a state array and keep the reference to an element on it?
why don't you just use an actual ref, from the `useRef` hook? More on reddit.com
๐ŸŒ r/react
11
3
September 5, 2023
People also ask

How do you update an array of objects in React state?
To update an array of objects in React state, use the useState hook to create a new array with the updated objects and then set the state with this new array.
๐ŸŒ
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 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
๐ŸŒ
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]); ...
๐ŸŒ
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 - Instead, when you want to update an object or array, you need to create a new one (or make a copy of an existing one), and then set the state to use that copy with mutation. Here is how to update react state correctly, particularly, object and array
๐ŸŒ
Pluralsight
pluralsight.com โ€บ tech insights & how-to guides โ€บ tech guides & tutorials
Manipulating Arrays and Objects in State with React | Pluralsight
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.
๐ŸŒ
Bobby Hadz
bobbyhadz.com โ€บ blog โ€บ react-update-object-in-array
How to Update an Array of Objects state in React | bobbyhadz
April 6, 2024 - You can also pass a function to the setState method that we get from the useState hook. The function gets called with the current state and can be used to update a specific object in the state array.
Find elsewhere
๐ŸŒ
ScriptVerse
scriptverse.academy โ€บ tutorials โ€บ reactjs-update-array-state.html
React/ReactJS: Update an Array State
The component <CheckingFruits/> renders three input checkboxes with values Apple, Mango and Pear. On check of each input, the respective values are stored as elements of this.state.fruit array. class CheckingFruits extends Component { constructor(props) { super(props); this.state = { fruits: [] } this.selectFruit = this.selectFruit.bind(this); } selectFruit(e) { if(e.target.checked) { this.setState({ fruits: [ ...this.state.fruits, e.target.value], }, () => { console.log(this.state.fruits); }); } } render() { return ( <div> <form> <input type="checkbox" id="apple" name="fruit" value="Apple" onClick={this.selectFruit}/>Apple <br/> <input type="checkbox" id="mango" name="fruit" value="Mango" onClick={this.selectFruit}/>Mango <br/> <input type="checkbox" id="pear" name="fruit" value="Pear" onClick={this.selectFruit}/>Pear <br/> </form> </div> ); } }
๐ŸŒ
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 - Then, within that profile, we map over the attributes array to find and update the correct attribute. This ensures that we're not directly mutating the state, but rather creating new arrays and objects as needed. The useState hook is a fundamental hook in React that allows you to add state to functional components.
๐ŸŒ
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.
Top answer
1 of 16
448

Here's how you can do it without helper libs:

handleChange: function (e) {
    // 1. Make a shallow copy of the items
    let items = [...this.state.items];
    // 2. Make a shallow copy of the item you want to mutate
    let item = {...items[1]};
    // 3. Replace the property you're intested in
    item.name = 'newName';
    // 4. Put it back into our array. N.B. we *are* mutating the array here, 
    //    but that's why we made a copy first
    items[1] = item;
    // 5. Set the state to our new copy
    this.setState({items});
},

You can combine steps 2 and 3 if you want:

let item = {
    ...items[1],
    name: 'newName'
}

Or you can do the whole thing in one line:

this.setState(({items}) => ({
    items: [
        ...items.slice(0,1),
        {
            ...items[1],
            name: 'newName',
        },
        ...items.slice(2)
    ]
}));

Note: I made items an array. OP used an object. However, the concepts are the same.


You can see what's going on in your terminal/console:

โฏ node
> items = [{name:'foo'},{name:'bar'},{name:'baz'}]
[ { name: 'foo' }, { name: 'bar' }, { name: 'baz' } ]
> clone = [...items]
[ { name: 'foo' }, { name: 'bar' }, { name: 'baz' } ]
> item1 = {...clone[1]}
{ name: 'bar' }
> item1.name = 'bacon'
'bacon'
> clone[1] = item1
{ name: 'bacon' }
> clone
[ { name: 'foo' }, { name: 'bacon' }, { name: 'baz' } ]
> items
[ { name: 'foo' }, { name: 'bar' }, { name: 'baz' } ] // good! we didn't mutate `items`
> items === clone
false // these are different objects
> items[0] === clone[0]
true // we don't need to clone items 0 and 2 because we're not mutating them (efficiency gains!)
> items[1] === clone[1]
false // this guy we copied
2 of 16
146

You could use the update immutability helper for this:

this.setState({
  items: update(this.state.items, {1: {name: {$set: 'updated field name'}}})
})

Or if you don't care about being able to detect changes to this item in a shouldComponentUpdate() lifecycle method using ===, you could edit the state directly and force the component to re-render - this is effectively the same as @limelights' answer, as it's pulling an object out of state and editing it.

this.state.items[1].name = 'updated field name'
this.forceUpdate()

Post-edit addition:

Check out the Simple Component Communication lesson from react-training for an example of how to pass a callback function from a state-holding parent to a child component which needs to trigger a state change.

๐ŸŒ
React
react.dev โ€บ learn โ€บ updating-objects-in-state
Updating Objects in State โ€“ React
Notice how much more concise the event handlers have become. You can mix and match useState and useImmer in a single component as much as you like. Immer is a great way to keep the update handlers concise, especially if thereโ€™s nesting in your state, and copying objects leads to repetitive code.
๐ŸŒ
Medium
dpericich.medium.com โ€บ how-to-update-complex-state-objects-in-react-c8cad3363566
How to Update Complex State Objects in React | by Daniel Pericich | Medium
October 6, 2022 - In order to keep track of state updates, we have to use either setState for class based components, or a custom โ€œset<StateObjectName>โ€ function for functional components. Both of these functions take a single argument, the variable representing ...
๐ŸŒ
Upmostly
upmostly.com โ€บ home โ€บ tutorials โ€บ how to update state onchange in an array of objects using react hooks
How To Update State onChange in an Array of Objects using React Hooks - Upmostly
September 17, 2022 - To update the state in an array of objects when the change occurs (onChange). We will create an array and store it inside the useState hook. Then, we will make a function updateState that will handle our onChange property.
๐ŸŒ
Robin Wieruch
robinwieruch.de โ€บ react-state-array-add-update-remove
How to manage React State with Arrays - Robin Wieruch
May 17, 2020 - One of the most common questions is how to add an item to an array in React state. Since you are not allowed to mutate the state directly, you cannot simply push an item to an array.
๐ŸŒ
Techiediaries
techiediaries.com โ€บ react-usestate-hook-update-array
Update Arrays with React useState Hook Without Push |
April 24, 2022 - In case, you want to use the first approach, you need to access the old array from the state object. ... <body> <div id="root"></div> <script> const { useState } = React; const App = () => { const [myArray, updateMyArray] = useState([]); const onClick = () => { updateMyArray( arr => [...arr, ...
๐ŸŒ
DEV Community
dev.to โ€บ raphaelchaula โ€บ how-to-update-object-or-array-state-in-react-4cma
How to update object or array state in React - DEV Community
January 21, 2021 - When you update the state, create a new array/object by destructuring the one in the state, manipulate it then set it as a new value in the state. import React, { useState } from 'react'; const States = () => { const [objectValue, setObjectValue] ...
๐ŸŒ
Reddit
reddit.com โ€บ r/react โ€บ is it possible to update a state array and keep the reference to an element on it?
r/react on Reddit: Is it possible to update a state array and keep the reference to an element on it?
September 5, 2023 -

So I know in React, when you have an array as a state, and you want to add/remove/update one of its elements, you have to create an entirely new array.

Cool, but what if I have an array of objects, one of which I'd like to keep an (updated) reference to? For example:

[arr, setArr] = useState()..
[ref, setRef] = useState()...

setRef(arr[5])
setArr(...) // set a new array equal to the old one, except arr[5] changes one property

// ref variable now still points to my old arr[5], not the new one.
// should I setRef(arr.find(f...)) to find my object again based on information I know is immutable? Would that work with the async nature of setStates?

Is there a way to accomplish this? If not, what should I do instead?

I just want to mutate a property in one object of my array and still keep a reference to that object.

Top answer
1 of 2
2

clickedSquare.on = !clickedSquare.on; is a state mutation. Don't mutate React state.

The reason the following code is likely working is because it has shallow copied the squares state array which triggers a rerender and exposes the mutated array elements.

function toggle(clickedSquare) {
  clickedSquare.on = !clickedSquare.on;        // <-- mutation!
  setSquares(prevSquares => [...prevSquares]); // new array for Reconciliation
}

It may not have any adverse effects in this specific scenario, but mutating state is a good foot gun and likely to cause potentially difficult bugs to debug/diagnose, especially if their effects aren't seen until several children deeper in the ReactTree.

Just always use the first method and apply the Immutable Update pattern. When updating any part of React state, even nested state, new array and object references need to be created for React's Reconciliation process to work correctly.

function toggle(clickedSquare) {
  setSquares(prevSquares => prevSquares.map((square) => // <-- new array
    square === clickedSquare
      ? { ...square, on: !square.on } // <-- new object
      : square
  ));
}
2 of 2
0

Here, You are using map() method which return only true or false for that condition. So, You should use filter() method instead of map() method which return filtered data for that condition.

For Example:

const arr = [
    {
        name: 'yes',
        age: 45
    },
    {
        nmae: 'no',
        age: 15
    }
]

const filterByMap = arr.map(elm => elm.age > 18)
console.log(filterByMap) // outputs --> [ true, false ]

const filterByFilter = arr.filter(elm => elm.age > 18)
console.log(filterByFilter) // outputs --> [ { name: 'yes', age: 45 } ]