From 872423cbddcb4b26d524c73702c914dd8b2fd2e3 Mon Sep 17 00:00:00 2001 From: philipcheung Date: Fri, 1 May 2026 17:23:27 +0800 Subject: [PATCH] add lazy loading attributes to images and fix potential runaway timers in main page scroll logic --- src/components/new_ui/CyclingImage.tsx | 20 +++++++++++----- src/components/new_ui/advantages.tsx | 1 + src/components/new_ui/hero1.tsx | 10 +++++--- src/components/new_ui/hero2.tsx | 3 +++ src/components/new_ui/info.tsx | 3 ++- src/components/new_ui/oilInfo.tsx | 2 ++ src/components/new_ui/truth.tsx | 6 ++++- src/pages/main.tsx | 33 ++++++++++++++------------ 8 files changed, 52 insertions(+), 26 deletions(-) diff --git a/src/components/new_ui/CyclingImage.tsx b/src/components/new_ui/CyclingImage.tsx index 492047f..9af3ecc 100644 --- a/src/components/new_ui/CyclingImage.tsx +++ b/src/components/new_ui/CyclingImage.tsx @@ -1,5 +1,5 @@ import { Box, Image, Button, HStack, VStack, Text } from '@chakra-ui/react' -import { useState, useEffect, CSSProperties } from 'react' +import { useState, useEffect, useMemo, useRef, CSSProperties } from 'react' interface CyclingImageProps { src: string @@ -49,6 +49,12 @@ const CyclingImage = ({ const [currentIntensity, setCurrentIntensity] = useState(intensity) const [currentImage, setCurrentImage] = useState(src) + // Keep refs to latest src/src2 so the setInterval callback is never stale + const srcRef = useRef(src) + const src2Ref = useRef(src2) + useEffect(() => { srcRef.current = src }, [src]) + useEffect(() => { src2Ref.current = src2 }, [src2]) + useEffect(() => { setSpeed(cycleDuration) }, [cycleDuration]) @@ -58,11 +64,12 @@ const CyclingImage = ({ if (!src2 || !isPlaying) return const interval = setInterval(() => { - setCurrentImage(prev => prev === src ? src2 : src) + // Use refs to read latest prop values, avoiding stale closures + setCurrentImage(prev => prev === srcRef.current ? src2Ref.current! : srcRef.current) }, speed * 1000) return () => clearInterval(interval) - }, [src, src2, speed, isPlaying]) + }, [src2, speed, isPlaying]) const togglePlayPause = () => { setIsPlaying(!isPlaying) @@ -76,9 +83,10 @@ const CyclingImage = ({ setCurrentIntensity(value) } - // CSS keyframes animation + // CSS keyframes animation — memoized so the