Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

184
Views
How to update an object and set the state with new object values using React or React Native

I am trying to update an object which is stored in my useState hook 'items'. Code block 1 does not work however code block 2 does. The only thing I did was put my items in a new variable. Can someone explain why code block 1 does not work however code block 2 does work.

Does NOT work

const Users = () => {
  const [items, setItems] = useState('');

  const folder = {
    id: itemId,
    title: text,
    location: itemLocation,
  };

  // get object index
  const objIndex = items.findIndex(obj => obj.location === itemLocation);

  // update object
  items[objIndex] = folder;

  // set state with update
  setItems([...items]);
};

Below works

const Users = () => {
  const [items, setItems] = useState('');

  const folder = {
    id: itemId,
    title: text,
    location: itemLocation,
  };

  // put state into variable
  const myItems = [...items]
  // get object index
  const objIndex = items.findIndex(obj => obj.location === itemLocation);

  // update object
  myItems[objIndex] = folder;

  // set state with update
  setItems(myItems);
};
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

items[objIndex] = folder;

You should never update state directly like this. React assumes you always use the "set" functions to update your state, and will not know when to re-render your components if you modify state directly.

https://reactjs.org/docs/state-and-lifecycle.html#do-not-modify-state-directly

about 4 years ago · Juan Pablo Isaza Report

0

  // update object
  items[objIndex] = folder;

I believe this is the problem. I actually never tried to change the state itself (I've always assumed it's read-only).

I will test this further later to be sure. But usually you don't edit the state directly (the state means the items variable). Either you 1) create an items1 such as items1 = { ...items } and then setItems(items1[objIndex] = folder) or you follow your approach in the second code snippet.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!