Code Eagle
Code Eagle

Reputation: 1242

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!

Upvotes: 3

Views: 4256

Answers (2)

Drew Reese
Drew Reese

Reputation: 203587

Your function is redefining your array shuffleCards each render. If you place the array into state it will be stable.

Define numbers and shuffle outside component as initial state and utility function

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

const shuffle = array => {
  // shuffle logic
};

Component logic: Initialize state and use the effect to shuffle the array on component mount

const CardShuffler = () => {
  const [shuffledCards] = useState(shuffle(numbers)); // initialize state

  return <Cards shuffledCards={shuffledCards} />;
};

Edit shuffle-cards

Upvotes: 1

hackape
hackape

Reputation: 20007

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} />
)

Upvotes: 4

Related Questions