Build a Wordle Clone Component in React
System DesignModel answerLast updated
Implement a 5-letter, 5-guess word puzzle in React with correct duplicate-letter tile scoring, virtual keyboard state, and clean game-over transitions.
Overview
You are building WordleGame, a self-contained React component that powers a word-guessing puzzle. The player has up to five attempts to identify a hidden five-letter word. After each guess the tiles and the on-screen keyboard update to reflect what the player has learned.
What to Build
1. The Game Board
- Render a grid of 5 rows × 5 tiles.
- The active row fills letter by letter as the player types.
- Pressing Enter on a complete five-letter row submits the guess.
- Pressing Backspace removes the last letter in the active row.
- Both the physical keyboard and the on-screen virtual keyboard must work.
- Once the game is over (win or loss), all input is ignored.
2. Tile Coloring Rules
After a guess is submitted, assign each tile one of three statuses:
| Status | Color | Meaning |
|---|---|---|
"correct" | Green | Right letter, right position |
"present" | Yellow | Right letter, wrong position |
"absent" | Gray | Letter not in word (or used up) |
Duplicate-letter rule: First, lock in every exact positional match as "correct". The remaining unmatched copies of each letter in the target form a budget. Hand out "present" status only while that budget lasts; any overflow copies are "absent". This ensures the total number of colored tiles for a given letter never exceeds how many times that letter appears in the target.
3. Virtual Keyboard & Game State
- The on-screen keyboard tracks the best-known status for every letter across all submitted guesses (
correctbeatspresentbeatsabsent). - When the player submits the exact target word, the game enters a won state.
- When five guesses are exhausted without a match, the game enters a lost state and reveals the target word.
4. Component Interface
interface WordleGameProps {
targetWord: string; // Guaranteed uppercase, exactly 5 ASCII letters, e.g. "REACT"
maxGuesses?: number; // Defaults to 5
onGameEnd?: (result: { won: boolean; guessCount: number }) => void;
}
export const WordleGame: React.FC<WordleGameProps> = (props) => {
// your implementation
};
Worked Example
Target: "APPLE" | Guess: "PUPPY"
- Pass 1 — exact matches: Index 2 is
P === P→correct. Remaining target letters available for matching:{ A:1, P:1, L:1, E:1 }. - Pass 2 — misplaced matches:
- Index 0
P: budget for P is 1, use it →present(budget → 0). - Index 1
U: no U in remaining →absent. - Index 3
P: budget exhausted →absent. - Index 4
Y: no Y in remaining →absent.
- Index 0
Final: [present, absent, correct, absent, absent]
Edge Cases to Handle
- Enter pressed with fewer than 5 letters typed → do nothing.
- Typing a 6th letter → ignore it.
- Non-alphabetic keys (digits, symbols, arrows) → ignore.
- Keyboard shortcuts with
Ctrl/Meta/Alt→ skip, so browser shortcuts still work. - Lowercase physical key input → normalize to uppercase.
onGameEndmust fire exactly once even under React StrictMode.- To reset the puzzle with a new word, the parent should remount via
key={targetWord}.
Hints
Hint 1
For the scoring function, two passes beat one: a first pass claims every exact match and tallies leftover target letters, then a second pass awards 'present' only while the tally for that letter is above zero. A single pass cannot handle duplicates correctly because you don't yet know which copies will be exact matches.
Hint 2
Store only the raw facts in state — the list of submitted guesses and the letters typed so far in the current row. Everything else (tile colors, keyboard colors, won/lost) is derived during render with useMemo, so it can never drift out of sync.
Hint 3
Use useReducer instead of multiple useState calls. The reducer becomes the single enforcement point for all input rules (full row before submit, no input after game over, letters only). It also solves the stale-closure problem: the keydown listener can dispatch without closing over state, so it only needs to be re-registered when targetWord or maxGuesses change, not on every keystroke.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
There are three largely independent sub-problems: a pure scoring function, a minimal state machine, and a single input pipeline. Solving them in isolation makes the overall component easy to reason about.
1. The Scoring Function
evaluateGuess(guess, target) runs two passes over the word length (always 5, so effectively O(1) in practice, O(L) in general).
Pass 1 — exact matches. Walk every index. If guess[i] === target[i], mark index i as "correct" and move on. Otherwise, add target[i] to a remaining frequency map. This map represents letters in the target that are still available to be matched as "present".
Pass 2 — misplaced matches. Walk every index not already marked "correct". Look up guess[i] in remaining. If the count is above zero, mark the tile "present" and decrement the count. Otherwise the tile stays "absent".
Why two passes? Because exact matches must be credited before any "present" can be issued. If you process left to right in one pass, an early misplaced copy can consume budget that a later exact match actually deserves, producing wrong colors.
Tracing APPLE / PUPPY:
- Pass 1: index 2 is exact (
P).remaining = {A:1, P:1, L:1, E:1}. - Pass 2: index 0
P→ present, P budget → 0. Index 1U→ absent. Index 3P→ absent (budget gone). Index 4Y→ absent. - Result:
[present, absent, correct, absent, absent]✓
2. State Design
Keep state minimal:
interface State { guesses: string[]; current: string }
guesses is the ordered list of submitted words. current is the in-progress row. That's it. Tile statuses, keyboard colors, and won/lost are all derived with useMemo at render time, so they are always consistent with guesses.
Use useReducer rather than multiple useState calls. The reducer is the single place that enforces every game rule:
- Enter: only accepted if
current.length === target.length; pushes toguessesand resetscurrent. - Backspace: trims the last character; no-ops on an empty row.
- Letter: appended only if
current.length < target.lengthand the key matches/^[A-Z]$/. - Game over: if
wonorlost, the reducer returns state unchanged regardless of the key. This blocks both physical and virtual keyboard input with no extra conditional logic in the component.
3. Input Pipeline
Both physical keys and on-screen button clicks funnel through a single press(key) function that uppercases the key and dispatches. The keydown handler skips events that carry Ctrl, Meta, or Alt modifiers so browser shortcuts remain functional. Enter and Backspace call preventDefault() to prevent on-screen buttons from receiving a synthetic click when they happen to hold focus.
press is memoized with useCallback on [target, maxGuesses]. The useEffect that registers the keydown listener depends only on press, so it never re-registers on every keystroke — a common performance mistake.
4. Derived Values
const evaluations = useMemo(
() => guesses.map(g => evaluateGuess(g, target)),
[guesses, target]
);
const keyStatus = useMemo(() => {
const map: Record<string, Status> = {};
guesses.forEach((g, r) =>
evaluations[r].forEach((s, i) => {
const prev = map[g[i]];
if (!prev || RANK[s] > RANK[prev]) map[g[i]] = s;
})
);
return map;
}, [guesses, evaluations]);
const won = guesses.includes(target);
const lost = !won && guesses.length >= maxGuesses;
RANK maps absent → 1, present → 2, correct → 3. The keyboard always shows the best status seen for each letter.
5. onGameEnd Exactly Once
Under React StrictMode, effects run twice in development. Guard with a ref:
const reported = useRef(false);
useEffect(() => {
if ((won || lost) && !reported.current) {
reported.current = true;
onGameEnd?.({ won, guessCount: guesses.length });
}
}, [won, lost]);
Full Implementation
import React, {
useCallback, useEffect, useMemo, useReducer, useRef,
} from "react";
type Status = "correct" | "present" | "absent";
interface WordleGameProps {
targetWord: string;
maxGuesses?: number;
onGameEnd?: (result: { won: boolean; guessCount: number }) => void;
}
export function evaluateGuess(guess: string, target: string): Status[] {
const n = target.length;
const result: Status[] = Array(n).fill("absent");
const remaining: Record<string, number> = {};
// Pass 1: exact matches
for (let i = 0; i < n; i++) {
if (guess[i] === target[i]) {
result[i] = "correct";
} else {
remaining[target[i]] = (remaining[target[i]] ?? 0) + 1;
}
}
// Pass 2: misplaced matches
for (let i = 0; i < n; i++) {
if (result[i] === "correct") continue;
const ch = guess[i];
if (remaining[ch] > 0) {
result[i] = "present";
remaining[ch]--;
}
}
return result;
}
const RANK: Record<Status, number> = { absent: 1, present: 2, correct: 3 };
const TILE_STYLE: Record<Status | "empty" | "active", React.CSSProperties> = {
empty: { background: "#fff", border: "2px solid #ccc" },
active: { background: "#fff", border: "2px solid #888" },
correct: { background: "#6aaa64", border: "2px solid #6aaa64", color: "#fff" },
present: { background: "#c9b458", border: "2px solid #c9b458", color: "#fff" },
absent: { background: "#787c7e", border: "2px solid #787c7e", color: "#fff" },
};
const KEY_ROWS = [
"QWERTYUIOP".split(""),
"ASDFGHJKL".split(""),
["ENTER", ..."ZXCVBNM".split(""), "⌫"],
];
interface State { guesses: string[]; current: string }
type Action = { key: string; target: string; maxGuesses: number }
function reducer(state: State, { key, target, maxGuesses }: Action): State {
const won = state.guesses.includes(target);
const lost = !won && state.guesses.length >= maxGuesses;
if (won || lost) return state;
if (key === "ENTER") {
if (state.current.length !== target.length) return state;
return { guesses: [...state.guesses, state.current], current: "" };
}
if (key === "BACKSPACE") {
return { ...state, current: state.current.slice(0, -1) };
}
if (/^[A-Z]$/.test(key) && state.current.length < target.length) {
return { ...state, current: state.current + key };
}
return state;
}
export const WordleGame: React.FC<WordleGameProps> = ({
targetWord,
maxGuesses = 5,
onGameEnd,
}) => {
const target = targetWord.toUpperCase();
const [{ guesses, current }, dispatch] = useReducer(reducer, {
guesses: [],
current: "",
});
const press = useCallback(
(raw: string) => {
const key = raw === "⌫" ? "BACKSPACE" : raw.toUpperCase();
dispatch({ key, target, maxGuesses });
},
[target, maxGuesses],
);
useEffect(() => {
const onKeyDown = (e: KeyboardEvent) => {
if (e.ctrlKey || e.metaKey || e.altKey) return;
if (e.key === "Enter" || e.key === "Backspace") e.preventDefault();
press(e.key === "Enter" ? "ENTER" : e.key === "Backspace" ? "BACKSPACE" : e.key);
};
window.addEventListener("keydown", onKeyDown);
return () => window.removeEventListener("keydown", onKeyDown);
}, [press]);
const evaluations = useMemo(
() => guesses.map(g => evaluateGuess(g, target)),
[guesses, target],
);
const keyStatus = useMemo(() => {
const map: Record<string, Status> = {};
guesses.forEach((g, r) =>
evaluations[r].forEach((s, i) => {
const prev = map[g[i]];
if (!prev || RANK[s] > RANK[prev]) map[g[i]] = s;
}),
);
return map;
}, [guesses, evaluations]);
const won = guesses.includes(target);
const lost = !won && guesses.length >= maxGuesses;
const reported = useRef(false);
useEffect(() => {
if ((won || lost) && !reported.current) {
reported.current = true;
onGameEnd?.({ won, guessCount: guesses.length });
}
}, [won, lost, guesses.length, onGameEnd]);
const tileBase: React.CSSProperties = {
width: 60, height: 60, display: "flex",
alignItems: "center", justifyContent: "center",
fontSize: 24, fontWeight: "bold", userSelect: "none",
borderRadius: 4,
};
return (
<div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 8 }}>
{/* Board */}
<div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
{Array.from({ length: maxGuesses }, (_, row) => {
const submitted = row < guesses.length;
const isActive = row === guesses.length;
return (
<div key={row} style={{ display: "flex", gap: 6 }}>
{Array.from({ length: target.length }, (_, col) => {
let letter = "";
let styleKey: Status | "empty" | "active" = "empty";
if (submitted) {
letter = guesses[row][col];
styleKey = evaluations[row][col];
} else if (isActive) {
letter = current[col] ?? "";
styleKey = letter ? "active" : "empty";
}
return (
<div key={col} style={{ ...tileBase, ...TILE_STYLE[styleKey] }}>
{letter}
</div>
);
})}
</div>
);
})}
</div>
{/* Status message */}
{won && <p style={{ fontWeight: "bold", color: "#6aaa64" }}>You got it!</p>}
{lost && <p style={{ fontWeight: "bold", color: "#e74c3c" }}>The word was {target}.</p>}
{/* Virtual keyboard */}
<div style={{ display: "flex", flexDirection: "column", gap: 6, marginTop: 12 }}>
{KEY_ROWS.map((row, r) => (
<div key={r} style={{ display: "flex", gap: 4, justifyContent: "center" }}>
{row.map(k => {
const s = keyStatus[k];
const bg =
k === "ENTER" || k === "⌫"
? "#d3d6da"
: s === "correct" ? "#6aaa64"
: s === "present" ? "#c9b458"
: s === "absent" ? "#787c7e"
: "#d3d6da";
return (
<button
key={k}
onClick={() => press(k)}
style={{
minWidth: k.length > 1 ? 56 : 40,
height: 56,
background: bg,
color: s && s !== undefined ? "#fff" : "#000",
border: "none",
borderRadius: 4,
fontWeight: "bold",
fontSize: 13,
cursor: "pointer",
}}
>
{k}
</button>
);
})}
</div>
))}
</div>
</div>
);
};
Complexity
| Time | Space | |
|---|---|---|
| Score one guess | O(L) | O(L) — bounded by 26 |
| Full board re-evaluation | O(G·L) per render | O(G·L) for stored guesses |
| Keyboard map | O(G·L) | O(26) |
With L = 5 and G ≤ 5, all costs are effectively constant.
Common Mistakes
- Single-pass scoring — cannot correctly handle duplicates because exact-match budget isn't known until the whole word is scanned.
- State explosion — storing derived values like
tileColorsin state means they can desync fromguesses. - Stale closure on
keydown— registering the listener inside auseEffectthat depends on state causes it to re-register every keystroke, or worse, capture stale state.useReducer+useCallbackon[target, maxGuesses]solves this cleanly. onGameEndfiring twice — React StrictMode intentionally double-invokes effects in development; theuseRefguard is necessary.- No modifier-key guard — omitting the
ctrlKey/metaKeycheck intercepts browser shortcuts like Cmd+R.