0

I have an array declared like this :

const [myArray,setMyArray] = useState([]);

I want to add a value in myArray and I found two methods for that:

Solution1: setMyArray([...myArray,value]);

Solution2: setMyArray(myArray => [...myArray,value]);

I read that these two solutions are not exactly the same and can give different results in some case. Can you please explain to me the exact difference between the two in a simple way?

  • 1
    Use the arrow function, so that it actually references the most updated value when the function is invoked. – Terry Sep 19 '21 at 13:47
  • can you please explain further – colder programmer Sep 19 '21 at 13:51
  • Because the new state is dependent on the previous state (same array with a new element added to it). It’s called a functional update: [read the docs here](https://reactjs.org/docs/hooks-reference.html#functional-updates) – Terry Sep 19 '21 at 13:57

0 Answers0