React variable change but it shouldn't

I have a problem for like 3 hours, and i don’t understand why,

The code below should explain my problem:

import {useEffect} from 'react'

function shuffle(tab) {
  console.table(tab) //shows initialdata
  var i, j, tmp;
  for (i = tab.length - 1; i > 0; i--) {
      j = Math.floor(Math.random() * (i + 1));
      tmp = tab[i];
      tab[i] = tab[j];
      tab[j] = tmp;
  }
  return tab;
}

function App() {

  useEffect(() => {
    const initaldata = [{a:1}, {a:2}, {a:3}, {a:5}]
    console.table(initaldata) //shows initialdata
    const finaldata = initaldata 
    console.table(shuffle(finaldata)) //shows initialdata shuffled
    console.table(initaldata) //shows initialdata shuffled,  why ?

  }, [])
  return null;
}

I tried multiples solutions like isolated "shuffle(initialdata)" in a function.

The fact that the shuffle function update all my variable makes all my code works bad.

Thank you and i hope you will find a solution.
(and sorry if there are some mistakes, im french)

2 thoughts on “React variable change but it shouldn't”

  1. JavaScript pass them objects by reference, that’s why. If you want to avoid that change the for loop with a map

    ....
    const toReturn = tab.map(item =>{
    ...
    });
    
    return toReturn
    
    Reply

Leave a Comment