Shuffle the Cards
Explore how to implement a shuffleCard function to randomize card pairs in a ReactJS memory game. Learn useState and useEffect hooks for managing shuffled cards and turns, and understand the logic behind using Math.random to ensure random order in the Asia Explorer game.
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 ...