Skip to content

UI Library for Design Engineers. Animated components and effects you can copy and paste into your apps. Free. Open Source.

Cancelling animation frame in particles.tsx on rerender (#396)

Khongchai Greesuradej101c0d8efe7e
diff --git a/registry/default/magicui/particles.tsx b/registry/default/magicui/particles.tsx
index 3ce2a292..c476fd4a 100644
--- a/registry/default/magicui/particles.tsx
+++ b/registry/default/magicui/particles.tsx
@@ -76,6 +76,7 @@ const Particles: React.FC<ParticlesProps> = ({
const mouse = useRef<{ x: number; y: number }>({ x: 0, y: 0 });
const canvasSize = useRef<{ w: number; h: number }>({ w: 0, h: 0 });
const dpr = typeof window !== "undefined" ? window.devicePixelRatio : 1;
+ const rafID = useRef<number | null>(null);
useEffect(() => {
if (canvasRef.current) {
@@ -86,6 +87,9 @@ const Particles: React.FC<ParticlesProps> = ({
window.addEventListener("resize", initCanvas);
return () => {
+ if (rafID.current != null) {
+ window.cancelAnimationFrame(rafID.current);
+ }
window.removeEventListener("resize", initCanvas);
};
}, [color]);
@@ -266,7 +270,7 @@ const Particles: React.FC<ParticlesProps> = ({
// update the circle position
}
});
- window.requestAnimationFrame(animate);
+ rafID.current = window.requestAnimationFrame(animate);
};
return (