Shuffle the Cards

Learn to use the spread and random methods to shuffle the cards.

In the shuffleCard function, we shuffle our CardImages in a random order and use the button in the Header component to create a new game any time a user clicks it. To define the shuffleCard function, we use CardImages, which is a collection of flags from various countries that have already been passed for us to use in the App.js component. We use the spread operator two times to create the array of image pairs. This is because we need to select two similar images. We use JavaScript’s Math.random() method because we want the images to be placed in random order.

Define the shuffleCard function

Let’s start by importing the useState and useEffect hooks to handle our state of shuffled-card order and turns, which is the number of turns the user took to guess the correct pair of images. The useEffect hook calls the ...