Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to shuffle an array once in functional react component?

I am creating a memory game, i have a shuffle function that shuffles an array of numbers, these numbers are rendered as cards, the problem is that the cards are shuffled every time state changed, i need to only initialize my component with a shuffled array that persists even state is changed!

i tried useEffect, but it doesn't work, or i couldn't implement it correctly

code:

const numbers = [1, 2, 3, 1, 2, 3];

const shuffle = (arr) => {
//shuffle logic here
}

let shuffledCards;
useEffect(() => {
   shuffledCards = shuffle(numbers) // it doesn't help
}, [])

return(
  <cards shuffledCards={shuffledCards} />
)

how can i shuffle my array once instead of every time state is changed!

like image 651
Code Eagle Avatar asked Apr 09 '26 15:04

Code Eagle


1 Answers

You can use useMemo hook.

const shuffle = (arr) => {
  //shuffle logic here
}

const shuffledCards = React.useMemo(() => {
  const numbers = [1, 2, 3, 1, 2, 3];  
  return shuffle(numbers);
}, [])

return (
  <cards shuffledCards={shuffledCards} />
)
like image 113
hackape Avatar answered Apr 11 '26 05:04

hackape



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!