Skip to content

Commit 7997b04

Browse files
tmikovclaude
andcommitted
[BouncingBall] Replace useRef() with closure variables
Move velocity state inside useEffect where it belongs, eliminating unnecessary useRef indirection. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
1 parent 178b68a commit 7997b04

File tree

1 file changed

+11
-12
lines changed

1 file changed

+11
-12
lines changed

examples/showcase/BouncingBall.jsx

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
// See LICENSE file for full license text
44

55
// Bouncing ball component - demonstrates custom drawing with rect and circle
6-
import React, { useState, useEffect, useRef } from 'react';
6+
import React, { useState, useEffect } from 'react';
77

88
export function BouncingBall() {
99
// Content dimensions
@@ -16,30 +16,29 @@ export function BouncingBall() {
1616
const [ballX, setBallX] = useState(200);
1717
const [ballY, setBallY] = useState(150);
1818

19-
// Initialize velocity with random angle (use single angle for both components)
20-
const speed = 5.0;
21-
const angle = Math.random() * 2 * Math.PI;
22-
23-
const vx = useRef(Math.cos(angle) * speed);
24-
const vy = useRef(Math.sin(angle) * speed);
25-
2619
// Update ball position every animation frame
2720
useEffect(() => {
21+
// Initialize velocity with random angle
22+
const speed = 5.0;
23+
const angle = Math.random() * 2 * Math.PI;
24+
let vx = Math.cos(angle) * speed;
25+
let vy = Math.sin(angle) * speed;
26+
2827
let time = performance.now();
2928
let rafId;
3029
function render(t) {
3130
const dt = (t - time) / 10;
3231
time = t;
3332

3433
setBallX((prevX) => {
35-
let newX = prevX + vx.current * dt;
34+
let newX = prevX + vx * dt;
3635

3736
// Bounce off left/right walls
3837
if (
3938
newX - ballRadius <= borderThickness ||
4039
newX + ballRadius >= contentWidth - borderThickness
4140
) {
42-
vx.current = -vx.current;
41+
vx = -vx;
4342
// Clamp position to stay within bounds
4443
newX =
4544
newX - ballRadius <= borderThickness
@@ -51,14 +50,14 @@ export function BouncingBall() {
5150
});
5251

5352
setBallY((prevY) => {
54-
let newY = prevY + vy.current * dt;
53+
let newY = prevY + vy * dt;
5554

5655
// Bounce off top/bottom walls
5756
if (
5857
newY - ballRadius <= borderThickness ||
5958
newY + ballRadius >= contentHeight - borderThickness
6059
) {
61-
vy.current = -vy.current;
60+
vy = -vy;
6261
// Clamp position to stay within bounds
6362
newY =
6463
newY - ballRadius <= borderThickness

0 commit comments

Comments
 (0)