Skip to content

Instantly share code, notes, and snippets.

@decagondev
Created April 23, 2025 22:21
Show Gist options
  • Save decagondev/64103250f295170ef3b353952c1bd688 to your computer and use it in GitHub Desktop.
Save decagondev/64103250f295170ef3b353952c1bd688 to your computer and use it in GitHub Desktop.

Fix the Bug – React + Three.js Canvas Game

Problem / Spec

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.


Reproduce the Issue

Bug: Cube stutters or moves inconsistently when holding left/right keys.

Suspect:

  • Input handler using onKeyDown and useState
  • React re-renders interfere with Three.js render loop

Starter Code (Simplified)

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>
  );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment