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

125
Views
Javascript / ReactJS Objects not copying as expected

Given the following code:

I am expecting staticData not to change when gridData does.

import { useState } from "react";
import "./styles.css";

const CheckData = (props) => {
  return (
    <>
      <h1>Data From {props.ds}</h1>
      {props.items.map((row) => (
        <div key={row.recordid}>{row.companyname}</div>
      ))}
    </>
  );
};

export default function App() {
  const [gridData, setGridData] = useState([
    {recordid: 1,companyname: "Devshare"},
    {recordid: 2,companyname: "Shufflebeat"},
    {recordid: 3,companyname: "Mita"}
  ]);

  const staticData = [...gridData];

  const changeValue = () => {
    let nd = gridData;
    nd[2]["companyname"] = "Superman";
    setGridData([...nd]);
  };

  return (
    <div className="App">
      <CheckData ds="gridData" items={gridData} />
      <CheckData ds="staticData" items={staticData} />
      <button style={{ marginTop: "50px" }} onClick={changeValue}>
        Change a value in gridData
      </button>
    </div>
  );
}

Why does value in staticData change when gridData does? I thought I made a copy of the object - not create an instance.

Code SandBox Test Code Here

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Based on a comment on the question:

staticData is suppose to be a "history" table allowing users to undo things.

Then you're building it in the wrong place. When you do this in the component:

const staticData = [...gridData];

Then on every render you re-build staticData based on the current values in gridData. So when the gridData state is updated and the component re-renders, you build a new staticData with the new values.

If staticData is supposed to be unchanging hard-coded data, define it outside the component:

const staticData = [
  {recordid: 1,companyname: "Devshare"},
  {recordid: 2,companyname: "Shufflebeat"},
  {recordid: 3,companyname: "Mita"}
];

And then within the component use it as the initial state value for gridData:

export default function App() {
  const [gridData, setGridData] = useState(staticData);

  //...
};

That way staticData is only defined once in the module. gridData can be updated in state as many times as you like but that won't affect staticData.

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!