You still don't want to mutate state. So if your state is an object, you'll want to create a new object and set with that. This may involve spreading the old state. For example:

const [person, setPerson] = useState({ name: 'alice', age: 30 });

const onClick = () => {
  // Do this:
  setPerson(prevPerson => {
    return { 
      ...prevPerson, 
      age: prevPerson.age + 1 
    }
  })
  // Not this:
  //setPerson(prevPerson => {
  //  prevPerson.age++;
  //  return prevPerson;
  //});
}

That said, using hooks you often no longer need your state to be an object, and can instead use useState multiple times. If you're not using objects or arrays, then copying is not needed, so spreading is also not needed.

const [name, setName] = useState('alice');
const [age, setAge] = useState(30);

const onClick = () => {
  setAge(prevAge => prevAge + 1);
}
Answer from Nicholas Tower on Stack Overflow
🌐
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.

Discussions

reactjs - Spread operator in React .setState() in the useState Hook - Stack Overflow
Why is the spread operator used in setName() function how does it work. What this code does is it takes the input from the user and displays it on the screen but before using spread operator the 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
I think I have a fundamental misunderstanding of useState inside useEffect.
SetState is async, you need use useeffect for setSelectedItem ans setSize when the items array change. UseEffect(() => { SetSelectedItem(items[0]); SetSize(items[0].size); },[items]) More on reddit.com
🌐 r/react
26
5
April 11, 2022
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
🌐
Medium
medium.com › @doplax › reactive-strategies-mastering-usestate-and-useeffect-with-the-spread-operator-518f0d0d1e35
Reactive Strategies: Mastering useState and useEffect with the Spread Operator | by Pol Valle (Doplax) | Medium
December 3, 2023 - This is where the spread operator starts to shine. Using [...tweets] allows us to create a copy of the tweets array. It’s particularly useful when we want to modify this array (like adding or removing elements) before updating the state. This ensures we are working with a new reference, allowing React to detect the change and update the UI.
🌐
JavaScript in Plain English
javascript.plainenglish.io › forms-in-react-with-hooks-809a3f38ed4
Forms in React with Hooks. How to use spread operator and hooks to… | by Saranjeet Singh | JavaScript in Plain English
May 26, 2022 - How to use the spread operator to properly display the values a user provides in the input form. In this app, we will add a person’s first and last name to a contact list with the use of React useState hook.
🌐
Stack Overflow
stackoverflow.com › questions › 68826619 › spread-operator-in-react-setstate-in-the-usestate-hook
reactjs - Spread operator in React .setState() in the useState Hook - Stack Overflow
First Name gets erased when last name was entered why did this happen and when using spread operator it provides the previous value and the code works perfect I want to know the logic behind this. Copyimport React from "react"; const Count2 = () => { const [name, setName] = React.useState({ firstName: " ", lastName: " " }); return ( <div> <input type="text" value={name.firstName} onChange={(e) => setName({ ...name, firstName: e.target.value })} /> <input type="text" value={name.lastName} onChange={(e) => setName({ ...name, lastName: e.target.value })} /> <h2>Your first Name is - {name.firstName}</h2> <h2>Your first Name is - {name.lastName}</h2> </div> ); }; export default Count2; reactjs ·
🌐
W3Schools
w3schools.com › react › react_es6_spread.asp
React ES6 Spread Operator
React Compiler React Quiz React Exercises React Syllabus React Study Plan React Server React Interview Prep React Bootcamp ... The JavaScript spread operator (...) copies all or part of an existing array or object into another array or object.
🌐
DEV Community
dev.to › a_ramesh › what-i-learned-today-in-react-usestate-spread-operator-map-function-2jm6
What I Learned Today in React: useState, Spread Operator & Map Function... - DEV Community
June 17, 2025 - import React, { useState } from ... the setCount function. The spread operator helps us create copies of arrays or objects and add new values without changing the original....
Find elsewhere
🌐
Medium
medium.com › @osamakhann118 › how-to-update-object-with-usestate-how-to-add-object-or-fields-in-array-of-objects-in-usestate-4af5459555d0
How to update object with useState | How to add object or fields in array of objects in useState | spread operator | by Osama khan | Medium
April 12, 2022 - React Native Hooks useState · if you have a array of objects or objects with fields and values, and you want to add more fields or items in that you can do it by using the following instruction. lets take a example, suppose we have following state with objects: const [values, setValues] = useState({ full_name: "", email: "", password: "", confirmPassword: "", type: "" }); and we only want to update value of email, we can do this by using Spread Operator: setValues({ ...values, email: 'new Value' }) similar with rest of the fields: setValues({ ...values, full_name: 'new Value' }) setValues({ ...values, password: 'new Value' }) setValues({ ...values, type: 'new Value' }) suppose you want to add a new field or object in the array or state, to achieve it we will follow the following method: setValues({ ...values, nickName: 'new Value' }) it will add a new field in the array ·
🌐
Medium
medium.com › @truongtronghai › spread-operator-ba867a0e97b4
Spread operator. Some ways to use it in React Js | by Truong Trong Hai | Medium
October 3, 2024 - }; const Card = ({ title, description ... state in a functional component using the useState hook, the spread operator can help merge the new state with the existing state....
🌐
DEV Community
dev.to › jamenamcinteer › all-the-hooks-series-usestate-3faf
All the Hooks Series: useState - DEV Community
June 5, 2020 - The other is to use the ES6 spread operator to create a new object with the values of the old object and any changes. For example, the following won't trigger a re-render since the existing state object is being mutated and to React / JavaScript, it's the same object. const Example = () => { const [item, setItem] = useState({id: 1, value: ''}); const editItem = () => { item.value = Math.random() * 100; setItem(item); } return ( <button onClick={editItem}>Change the number</button> ) } To make this work, a new object must be created.
🌐
Devhandbook
devhandbook.com › react › hooks › usestate
React Hook useState | Dev Handbook
import React, { useState } from 'react'; const UseStateObject = () => { const [person, setPerson] = useState({ name: 'Anna', age: 20, message: 'Random Message', }); const changeMessage = () => { setPerson({ ...person, message: 'Hello World' }); }; return ( <div> <h3>{person.name}</h3> <h3>{person.age}</h3> <h4>{person.message}</h4> <button className='btn' onClick={changeMessage}> Change message </button> </div> ); }; export default UseStateObject; To preserve all values in the object, we use spread operator: …person
🌐
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 - Mutating State Directly: One common mistake is to use the spread operator to mutate the state directly. In React, you should never mutate the state directly. Instead, you should always use setState (in class components) or the state update function returned by useState (in functional components) to update the state.
🌐
C# Corner
c-sharpcorner.com › article › usestate-hook-in-reactjs
useState() Hook In ReactJS
September 12, 2019 - This spread operator dictates the method that creates a replica of the whole object and just updates the followed property, Now check the output below, type the prefix for the name, ... Now state value is maintained and not lost.
🌐
Design+Code
designcode.io › react-hooks-handbook-spread-attributes
Spread attributes - React Hooks Handbook - Design+Code
Luckily, there's something called the spread operator - or spread attributes - that we can use, which only takes a few seconds to code! ... Purchase includes access to 50+ courses, 320+ premium tutorials, 300+ hours of videos, source files and certificates. ... Purchase includes access to 50+ courses, 320+ premium tutorials, 300+ hours of videos, source files and certificates. ... Download the videos and assets to refer and learn offline without interuption. ... An overview of React ...
🌐
Refine
refine.dev › home › blog › tutorials › 5 most common usestate mistakes react developers often make
5 Most Common useState Mistakes React Developers Often Make | Refine
May 24, 2024 - With this spread operator, you can easily unpack the properties of an existing item into a new item and, at the same time, modify or add new properties to the unpacked item. import { useState, useEffect } from "react"; export default function ...
🌐
Efficientcoder
efficientcoder.net › react-18-usestate-array
How to add a new value to React's array state - EfficientCoder
Array manipulation is simplified, but since state is immutable, specific methods are required when using React hooks. As a recap, because the state is immutable, we are unable to simply add a new value to the array in the same way that we would ordinarily do with regular JavaScript. Instead, we must make use of the setter function, which is returned by the call to useState, as well as the JavaScript spread operator or similar operators.
🌐
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?).
🌐
LogRocket
blog.logrocket.com › home › using react usestate with an object
Using React useState with an object - LogRocket Blog
June 4, 2024 - The spread operator (...) is a JavaScript feature for expanding an iterable (like an array or object) into individual elements.
🌐
DEV Community
dev.to › jackent2b › usestate-with-objects-what-the-hack-35d1
useState with objects (what the hack!!) - DEV Community
December 23, 2020 - Reason: This is happening because useState does not automatically merge and update the object (contrary to setState while using class-based components) i.e. useState does not merge the state automatically. We have to do it manually with the help of spread operator.
🌐
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 - Introduction In React.js, the three dots (...), commonly known as the spread operator, are a powerful tool for managing state, props, and arrays within your applications. The spread syntax simplifies many common tasks, such as merging objects, ...