Fix the Bug – React + Three.js Canvas Game
Avatar: Elena is building a small 3D mini-game in React + Three.js. It renders a basic scene with a player cube that can move left and right. But there’s a bug: the cube sometimes jumps or lags when key events fire rapidly, and the frame render isn't synced well with React state.
Application: A React + Three.js app where you need to fix a real rendering + input issue.
Bug: Cube stutters or moves inconsistently when holding left/right keys.
Suspect:
- Input handler using
onKeyDown
anduseState
- React re-renders interfere with Three.js render loop
import { Canvas, useFrame } from '@react-three/fiber';
import { useRef, useState, useEffect } from 'react';
function PlayerCube() {
const ref = useRef();
const [posX, setPosX] = useState(0);
useEffect(() => {
const handleKeyDown = (e) => {
if (e.key === 'ArrowLeft') setPosX((x) => x - 0.1);
if (e.key === 'ArrowRight') setPosX((x) => x + 0.1);
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, []);
useFrame(() => {
ref.current.position.x = posX;
});
return (
<mesh ref={ref} position={[0, 0, 0]}>
<boxGeometry args={[1, 1, 1]} />
<meshStandardMaterial color="orange" />
</mesh>
);
}
export default function Game() {
return (
<Canvas camera={{ position: [0, 0, 5] }}>
<ambientLight />
<PlayerCube />
</Canvas>
);
}