From 5cd4720ef2d3756d2f47368e873dd7e68f624e80 Mon Sep 17 00:00:00 2001 From: Josh Hawkins <32435876+hawkeye217@users.noreply.github.com> Date: Sat, 6 Jul 2024 17:59:50 -0500 Subject: [PATCH] Use a ref instead of a state and clear timeout in AutoUpdatingCameraImage --- .../camera/AutoUpdatingCameraImage.tsx | 26 ++++++++++--------- web/src/components/player/LivePlayer.tsx | 7 ++--- 2 files changed, 18 insertions(+), 15 deletions(-) diff --git a/web/src/components/camera/AutoUpdatingCameraImage.tsx b/web/src/components/camera/AutoUpdatingCameraImage.tsx index 3730f069b..ee0f6eccc 100644 --- a/web/src/components/camera/AutoUpdatingCameraImage.tsx +++ b/web/src/components/camera/AutoUpdatingCameraImage.tsx @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useState } from "react"; +import { useCallback, useEffect, useRef, useState } from "react"; import CameraImage from "./CameraImage"; type AutoUpdatingCameraImageProps = { @@ -22,7 +22,7 @@ export default function AutoUpdatingCameraImage({ }: AutoUpdatingCameraImageProps) { const [key, setKey] = useState(Date.now()); const [fps, setFps] = useState("0"); - const [timeoutId, setTimeoutId] = useState(); + const timeoutRef = useRef(null); useEffect(() => { if (reloadInterval == -1) { @@ -32,9 +32,9 @@ export default function AutoUpdatingCameraImage({ setKey(Date.now()); return () => { - if (timeoutId) { - clearTimeout(timeoutId); - setTimeoutId(undefined); + if (timeoutRef.current) { + clearTimeout(timeoutRef.current); + timeoutRef.current = null; } }; // we know that these deps are correct @@ -46,19 +46,21 @@ export default function AutoUpdatingCameraImage({ return; } + if (timeoutRef.current) { + clearTimeout(timeoutRef.current); + } + const loadTime = Date.now() - key; if (showFps) { setFps((1000 / Math.max(loadTime, reloadInterval)).toFixed(1)); } - setTimeoutId( - setTimeout( - () => { - setKey(Date.now()); - }, - loadTime > reloadInterval ? 1 : reloadInterval, - ), + timeoutRef.current = setTimeout( + () => { + setKey(Date.now()); + }, + loadTime > reloadInterval ? 1 : reloadInterval, ); // we know that these deps are correct // eslint-disable-next-line react-hooks/exhaustive-deps diff --git a/web/src/components/player/LivePlayer.tsx b/web/src/components/player/LivePlayer.tsx index 4a5bd8c02..5d3129ffe 100644 --- a/web/src/components/player/LivePlayer.tsx +++ b/web/src/components/player/LivePlayer.tsx @@ -256,9 +256,10 @@ export default function LivePlayer({ )}