Skip to content

Commit ee14dc3

Browse files
feat: optimize game component structure with useCallback and useMemo for performance improvements
1 parent f858794 commit ee14dc3

File tree

1 file changed

+21
-10
lines changed

1 file changed

+21
-10
lines changed

src/game.tsx

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { useEffect, useState } from "react";
1+
import { useCallback, useEffect, useMemo, useState } from "react";
22
import { Unity, useUnityContext, useUnityMetricsInfo } from "react-unity-webgl";
33
import "./game.css";
44

@@ -28,10 +28,13 @@ export function Game() {
2828
interval: 1000 / 60,
2929
});
3030

31-
function handleClickStart() {
31+
const handleClickStart = useCallback(() => {
32+
if (!isLoaded || isStarted) {
33+
return;
34+
}
3235
sendMessage("Controller", "StartGame");
3336
setIsStarted(true);
34-
}
37+
}, [isLoaded, isStarted, sendMessage]);
3538

3639
useEffect(() => {
3740
addEventListener("scoreDidUpdate", setScore);
@@ -40,19 +43,27 @@ export function Game() {
4043
};
4144
}, [addEventListener, removeEventListener]);
4245

46+
const rootClassname = useMemo(() => {
47+
let className = "game-container";
48+
if (isLoaded) {
49+
className += " is-loaded";
50+
}
51+
if (isStarted) {
52+
className += " is-started";
53+
}
54+
return className;
55+
}, [isLoaded, isStarted]);
56+
4357
return (
44-
<div className="game-container">
45-
<div className={["loading-overlay", isLoaded && "loaded"].join(" ")}>
58+
<div className={rootClassname}>
59+
<div className="heads-up-display">
4660
<img src="/game-logo.png" className="game-logo" alt="Game Logo" />
47-
<div className="loading-indicator-bar">
61+
<div className="loading-bar">
4862
<div
49-
className="loading-indicator-fill"
63+
className="loading-fill"
5064
style={{ width: `${loadingProgression * 100}%` }}
5165
/>
5266
</div>
53-
</div>
54-
<div className={["main-menu", isStarted && "started"].join(" ")}>
55-
<img src="/game-logo.png" alt="Game Logo" className="game-logo" />
5667
<img
5768
src="/start-button.png"
5869
alt="Start Button"

0 commit comments

Comments
 (0)