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

141
Views
React Hooks useState array storage problem

I have the following problem: I have a method that returns a multidimensional array in my Grids component. I would want to store any multidimensional array recomputed in a separate list. The problem is that when I am using my useState() declared in this way

const [listGrid,setListGrid] = useState<any[]>([])  

only the current state element is saved repeatedly in the array list. Follow the code of interest part :

const [listGrid,setListGrid] = useState<any[]>([]);
const grid= initGrid(); //initialise a new grid.
 const disableButtonHandler = ():void => {
       const cloneGrid =[...grid]
      console.log(cloneGrid===grid)//are no the same!!
      setListGrid(prevListGrid=>[...prevListGrid,cloneGrid]);
};

this is the snapshot of my list with the grids saved:

enter image description here

so, basically, all the arrays stored in listGrid are the same and I'd want to store any change of my computed list.

what could I do wrong with it? thanks in advance.

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

0

The matrix is represented by an array of arrays, while you are duplicating the containing array, the contained ones are still the same. Basically, cloneGrid[i] === grid[i] is true for 0 <= i < grid.length.

You can solve this by doing the following:

const cloneGrid = grid.map(row => [...row]);
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!