If you have an array of objects, and you want to update few properties of one of the objects inside the array. Then you could do something like this.

const index = state.findIndex(x => x.name === field);
if(index > -1) {
  const newState = [...state];
  newState[index] = { 
    ...newState[index],
    isValid: isValid,
    content: content,
    isUnchanged: false
  }
  setRequiredFields(newState);
}
  • Find the index of the object that you want to update.
  • Add properties inside that object.
  • Update the react state.
Answer from Ammar on Stack Overflow
🌐
freeCodeCamp
forum.freecodecamp.org › t › using-spread-operator-to-update-the-state-in-react › 351831
Using Spread operator to update the state in react - The freeCodeCamp Forum
February 20, 2020 - Hi, does copying nested object using spread have different address (reference). We do that so react can know while rendering the dom that there is some change (because of the references are different). But the value we u…
🌐
Medium
medium.com › @thejasonfile › using-the-spread-operator-in-react-setstate-c8a14fc51be1
Using the spread operator in React setState | by Jason Arnold | Medium
May 25, 2017 - That’s when I remembered the spread operator […]. The spread operator can be used to take an existing array and add another element to it while still preserving the original array (famous original array’s?).
Discussions

Spread operator to update array of objects - javascript
Update the react state. ... Sign up to request clarification or add additional context in comments. ... Find the answer to your question by asking. Ask question ... See similar questions with these tags. ... Introducing Stack Internal: Powering the human intelligence layer of... ... 0 How can the index of an object within an array be preserved when modifying an object property while using the spread operator... More on stackoverflow.com
🌐 stackoverflow.com
August 1, 2021
Need help with useState hook - can't update an array using the spread operator
Both versions look like they should work -- maybe it's something in the surrounding context? Can you share more and/or repro in a codepen? More on reddit.com
🌐 r/reactjs
9
2
December 5, 2021
reactjs - Why use the JavaScript spread operator to update an item in an array? - Stack Overflow
I'm just following an online course and I'm interested as to why the tutor would have used the spread operator to update an object in an array instead of just using the object itself? I've google... More on stackoverflow.com
🌐 stackoverflow.com
reactjs - Updating state array using Spread operator in React? - Stack Overflow
I am trying to update a state array after accepting the input from Form. State already has events object in it with data and I want to accept data from the form and append to the existing list. I'm... More on stackoverflow.com
🌐 stackoverflow.com
June 20, 2021
🌐
React
react.dev › learn › updating-arrays-in-state
Updating Arrays in State – React
In this way, spread can do the job of both push() by adding to the end of an array and unshift() by adding to the beginning of an array.
🌐
DhiWise
dhiwise.com › post › how-to-simplify-your-react-code-with-the-spread-operator
The Ultimate Guide To Using The React Spread Operator
October 31, 2023 - Immutable Data Handling: The spread operator helps in maintaining immutability in your React components. It creates a new array or object instead of mutating the existing one, which is a key principle in React.
🌐
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 - ... const handleAdd = (todo) => { const newTodos = todos.slice(); newTodos.push(todo); setTodos(newTodos); } The spread operator is syntactic sugar for creating a new copy of a reference.
🌐
Reddit
reddit.com › r/reactjs › need help with usestate hook - can't update an array using the spread operator
r/reactjs on Reddit: Need help with useState hook - can't update an array using the spread operator
December 5, 2021 -

I am fairly new to React and I think I am missing an important concept about state.

I am trying to update a state variable, specifically an array. The following function successfully updates the array if I use Array.push(), but not if I use destructuring/the spread operator. What am I missing? Also, the template is completely non-reactive - even when the console.log statement displays the correct value, the HTML does not.

function MyComponent() {
    const [selection, setSelection] = useState([]);

    const handleSelection = (id) => {
        // doesn't work
        // let newSelection = [...selection, id];

        let newSelection = selection;
        newSelection.push(id);

        // Prints the correct value when using Array.push() but not destructuring
        console.log(selection);

        setSelection(newSelection);
    };

    return (
        {/* never changes */}
        <pre>{JSON.stringify(selection, null, 2)}</pre>
    )
}

EDIT: I thought this was a problem with how I was setting state on the selection variable, but it turns out the issue was with other parts of my code that are tangentially related to this. The problem was that I was trying to to loop over some data and generate a component for each datum, but I wasn't doing that correctly. I was setting a different state variable to hold these components, and the various pieces of state were out of sync. Here is a repro of the working code, where I am mapping the components correctly (in the template directly rather than setting state, which seems to be better practice). As you can see, spread/destructuring works perfectly as expected now.

Find elsewhere
Top answer
1 of 3
4

The main reason I can see for this is to create a shallow copy of the object, so that if you perform any operations on the copy, it won't mutate the original. This would be especially useful in a functional programming paradigm where you don't want to mutate any shared objects/maintain a shared state.

However, as I mentioned, this only creates a shallow copy (as opposed to a deep copy), so that if any of the properties of the object are themselves mutable (such as an array property), then those properties would still be able to be mutated.

Edit: From the question in the comments, and building off of what @AdiH mentioned in their answer, it doesn't seem to make any sense to update post.title before creating the shallow copy as this would mutate the original object. It's possible that the author intended for this change to be reflected in both the original and the copy, but for any further changes to be reflected only in the copy

const x = { a: 'b', c: 'd', d: [] };

const copy = { ...x };
copy.a = 'c';
console.log(x); // unchanged

const same = x;
same.a = 'c';
console.log(x); // changed

copy.d.push('e');
console.log(x); // x.d has been changed

2 of 3
2

I can see your confusion. I think the example is not great. One can only guess what the author had in mind but if he or she intended to enforce immutability I would not have done post.title = "Updated" since it obviously mutates post.

Instead I would have done post[index] = { ...post, title: "Updated"} see examples of JS Spread syntax.

So yes, I'm also unable to guess the motivation behind that example.

🌐
CoreUI
coreui.io › blog › draft-how-to-replace-all-occurrences-of-a-string-in-javascript
Mastering the Spread Operator (<code>...</code>) in React.js · CoreUI
September 3, 2023 - This method is particularly effective ... React state, the spread operator simplifies the process of creating a new array that includes updates or additions without mutating the existing array....
🌐
Medium
medium.com › @fa22-bse-004 › how-to-use-the-spread-operator-in-react-eb6e071b57f4
How to use the spread operator (…) in React | by maryam hafeez | Medium
September 22, 2024 - However if we talk in reference to React, spread operator spreads an object of props onto an element in available in React component. ... A spread operator is denoted by three consecutive dots: … . ... If you want to work on multiple arrays ...
🌐
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 - But there was i little bit of problem in that . i was just pushing the object into the empty array at second index . So, there is little problem , i cannot just map over them straight. i have tell there index too. this.state.car[1].map((data, i) => (<ul key={i}><li> {data.name} </li><li> {data.price} </li></ul> then i found Spread syntax .
🌐
DEV Community
dev.to › edriso › using-the-spread-operator-in-react-426e
Using the Spread Operator in React - DEV Community
January 5, 2026 - In JavaScript, the spread operator (...) allows you to spread the properties of an object or elements of an array into individual items. In React, it's commonly used to pass all properties of an object as props to a component.
🌐
Medium
medium.com › @Fbnjnkr › react-state-updating-objects-and-arrays-in-state-with-the-spread-syntax-ead6a558de8b
React State: Updating objects and arrays in state with the spread syntax | by Fabian Janker | Medium
March 25, 2023 - Updating Objects in State — React || Updating Arrays in State — React ... You can use the spread syntax for arrays and objects to create copies of the values.
🌐
javascriptroom
javascriptroom.com › blog › spread-operator-in-react-setstate
Why Use the Spread Operator in React .setState()? (Even When the App Works Without It)
Even if your React app “works” without the spread operator, omitting it埋下隐患 (buries hidden risks). The spread operator ensures immutability, preserves nested state, avoids array mutation bugs, and makes state changes predictable—cr...