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

115
Views
Other way to modify state in react?

I have code example like this (codesandbox demo):

const [array, setArray] = useState([]);

  const addElementToArray = () => {
    array.push(1);
    setArray([...array]);
  }

  return (
    <div className="App">
      <button onClick={addElementToArray}>addElementToArray</button>
      {array.map(el => <div>{el}</div>)}
    </div >
  );

Here I dont use standard way of updating array like

setArray([...array, 1]);

What disadvantages of updating values like in my first example?

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

In this example you won't notice any problems. But then, this is a very small and contrived example, isn't it?

But in a larger application with more complex logic and functionality, this can easily lead to strange and difficult bugs. Why? Because you're directly mutating state:

array.push(1);

Does anything else hold a reference to that state or observe it in any way? Is this mutation happening in the middle of a component render, where some logic has already responded to the pre-mutated state and the remaining logic will respond to the post-mutated state? Are multiple state updates being queued and now we don't know which ones will see which version of state?

That's a lot to have to keep track of. Or you can avoid all of those potential problems by simply not mutating state and sticking with "the standard way" that you already know:

setArray([...array, 1]);

or, if there may be multiple state updates and you want to append the 1 to the most current:

setArray(a => [...a, 1]);
about 4 years ago · Santiago Trujillo Report

0

If you use this line alone,

array.push(1);

the state changes but React isn't aware of the change so the component won't rerender. In this case, the whole purpose of React is gone because the UI does not correspond to the state change, and that makes it a bad practice.

However, if you use this line alone:

setArray([...array, 1]);

the UI will correspond to the state change, which is the correct way of using React.

And regarding this:

array.push(1);
setArray([...array]);

you're basically mocking React because .push() changes the state without any rerender.

about 4 years ago · Santiago Trujillo 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!