From bb12eec7f99cb4c859b548b710c1de45caa09aea Mon Sep 17 00:00:00 2001 From: Paul Tagliamonte Date: Wed, 20 Sep 2023 15:40:56 -0400 Subject: [PATCH] Use useRef to store the Engine MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit useRef is a React Hook that lets you reference a value that’s not needed for rendering. The value is set to the initial value on startup, and will hang on to 'current' for us. We can store the Engine in the ref, and React will take care of persisting it for us. Signed-off-by: Paul Tagliamonte --- src/hooks/useSetupEngineManager.ts | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/src/hooks/useSetupEngineManager.ts b/src/hooks/useSetupEngineManager.ts index 3636dd431..cdd9cc767 100644 --- a/src/hooks/useSetupEngineManager.ts +++ b/src/hooks/useSetupEngineManager.ts @@ -1,4 +1,4 @@ -import { useLayoutEffect } from 'react' +import { useRef, useLayoutEffect } from 'react' import { _executor } from '../lang/executor' import { useStore } from '../useStore' import { EngineCommandManager } from '../lang/std/engineConnection' @@ -28,6 +28,7 @@ export function useSetupEngineManager( const quadWidth = Math.round(width / 4) * 4 const height = streamHeight ? streamHeight : 0 const quadHeight = Math.round(height / 4) * 4 + const eng = useRef(null) useLayoutEffect(() => { setStreamDimensions({ @@ -35,19 +36,21 @@ export function useSetupEngineManager( streamHeight: quadHeight, }) if (!width || !height) return - const eng = new EngineCommandManager({ - setMediaStream, - setIsStreamReady, - width: quadWidth, - height: quadHeight, - token, - }) - setEngineCommandManager(eng) - eng.waitForReady.then(() => { + if (eng.current === null) { + eng.current = new EngineCommandManager({ + setMediaStream, + setIsStreamReady, + width: quadWidth, + height: quadHeight, + token, + }) + } + setEngineCommandManager(eng.current) + eng.current.waitForReady.then(() => { executeCode() }) return () => { - eng?.tearDown() + eng.current?.tearDown() } }, [quadWidth, quadHeight]) }