Skip to content
Tutorials Center
My learning

Topics

Lesson 111 of 132 ยท Projects

Project: Memory Card Game

Build a memory card matching game in React. Shuffle a deck fairly, track flipped cards, handle matches with a timed flip-back, count moves and detect a win with derived state.

In a memory game you flip two cards at a time and try to find matching pairs. It is a compact way to practise the habits that make larger apps manageable: store the smallest possible state, derive everything else, and let an effect handle the one thing that happens after something else (flipping mismatched cards back).

We build it in three stages: a shuffled deck, the matching rules, and moves with a win screen and restart.

The plan

Each card is { id, face, matched }. The deck contains every face twice. Which cards are face up is stored as a small array of ids, flipped, holding zero, one or two entries. A card shows its face if it is matched or its id is in flipped. We never store a "faceUp" field on each card, because it would duplicate information we already have (choosing state structure).

Things we can derive during render, and therefore do not store: whether the game is won (cards.every(c => c.matched)) and whether the board is locked (flipped.length === 2).

Stage 1: a fair shuffle

A common mistake is array.sort(() => Math.random() - 0.5). It looks right but the comparison is inconsistent, so some orders are much more likely than others. The correct algorithm is Fisher-Yates: walk backwards, swapping each position with a random earlier one. We create the deck once with a lazy initial state (useState(makeDeck)) so shuffling does not repeat on every render (useState).

Stage 1: shuffled deck

Every card has a stable id that is its position at deal time, so it works as the list key.

Stage 2: matching

Clicking a card adds its id to flipped, unless the click should be ignored: the board is locked (two cards already up), or the card is already face up or matched. When two cards are up, an effect compares them. A match marks both cards as matched and clears flipped. A mismatch waits 800 ms so the player can see the second card, then clears flipped to flip both back.

Stage 2: flip and match

Two guards in flip deserve attention. The "locked" check stops a third click from corrupting the pair while the mismatch is still showing. And the includes check stops the player matching a card with itself by clicking it twice. The effect's cleanup clears the timer if the component goes away while waiting (effect cleanup).

The comparison could also live in the click handler. We use an effect here because the comparison is a reaction to "two cards are now face up", and the delay needs cleanup. Either choice is valid; the handler version avoids an extra render (you might not need an effect).

Stage 3: moves, winning and restart

A move is one pair of flips. Counting moves needs one more piece of state. The win condition is derived. Restarting must reset everything; a neat way is to move the game into its own component and change its key to throw away all its state at once (reconciliation).

Stage 3: the complete game

Notice the effect runs when flipped changes to a pair, and the setMoves there is safe because the effect only reacts once per pair (the following setFlipped([]) makes the length 0, which exits early).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is array.sort(() => Math.random() - 0.5) a poor shuffle?

    Sorting algorithms assume a consistent comparison. A random one makes some permutations far more likely than others. Fisher-Yates gives each order equal probability.
  2. 2. Which of these is derived rather than stored in this game?

    Winning is just cards.every(c => c.matched), so it can never disagree with the cards.
  3. 3. Why does flip return early when two cards are already flipped?

    While a mismatch is displayed the board is locked, otherwise the player could reveal more cards and confuse the logic.
  4. 4. How does changing the key of <Game> restart the game?

    A different key means a different component identity. The old instance is destroyed and the new one runs its initial state, including a new shuffle.

Summary

  • Shuffle with Fisher-Yates, and create the deck once with a lazy useState(initializer).
  • Store flipped ids and matched flags; compute "face up", "locked" and "won" during render.
  • Use an effect for the delayed flip-back and clean up the timer.
  • Guard click handlers against invalid moves (locked board, already open, already matched).
  • Restart by changing a key, which resets all state in that subtree.

Next: Project: Typing Speed Tester