I am using a function that takes an array as input and returns a shuffled array. When i return the shuffled array , the UI is not getting repainted. Code below –
import { useState } from "react";
function App() {
const [items, setItems] = useState([
"Amit",
"Ashok",
"Alok",
"Vijay",
"Kumar",
"Raju",
]);
console.log("App component is rendered");
function shuffle(array) {
let currentIndex = array.length;
// While there remain elements to shuffle...
while (currentIndex != 0) {
// Pick a remaining element...
let randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
// And swap it with the current element.
[array[currentIndex], array[randomIndex]] = [
array[randomIndex],
array[currentIndex],
];
}
//
console.log(array);
return array;
//return [...array];
}
console.log(items);
return (
<>
<button onClick={() => setItems(shuffle(items))}>Shuffle</button>
{items?.map((item) => (
<p key={item}>{item}</p>
))}
</>
);
}
export default App;
If i return the array using the spread operator , the UI is getting rendered again. Can anyone explain what is the reason for this.