From 6ae82cc70cbe42624305254a02529f725989d0de Mon Sep 17 00:00:00 2001 From: Axel Bocciarelli Date: Thu, 8 Feb 2024 11:19:41 +0100 Subject: [PATCH] Fix subtle stale state issue in `H5WasmProvider` When any of the props change, `App` gets rendered once with a stale API instance. --- packages/h5wasm/src/H5WasmProvider.tsx | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/packages/h5wasm/src/H5WasmProvider.tsx b/packages/h5wasm/src/H5WasmProvider.tsx index e115143d2..7ca29d5bd 100644 --- a/packages/h5wasm/src/H5WasmProvider.tsx +++ b/packages/h5wasm/src/H5WasmProvider.tsx @@ -1,7 +1,7 @@ import type { DataProviderApi } from '@h5web/app'; import { DataProvider } from '@h5web/app'; import type { PropsWithChildren } from 'react'; -import { useEffect, useState } from 'react'; +import { useMemo, useState } from 'react'; import { H5WasmApi } from './h5wasm-api'; import type { Plugin } from './utils'; @@ -16,17 +16,15 @@ interface Props { function H5WasmProvider(props: PropsWithChildren) { const { filename, buffer, getExportURL, getPlugin, children } = props; - const [api, setApi] = useState(); + const api = useMemo( + () => new H5WasmApi(filename, buffer, getExportURL, getPlugin), + [buffer, filename, getExportURL, getPlugin], + ); - useEffect(() => { - const h5wasmApi = new H5WasmApi(filename, buffer, getExportURL, getPlugin); - setApi(h5wasmApi); - - return () => void h5wasmApi.cleanUp(); - }, [filename, buffer, getExportURL, getPlugin]); - - if (!api) { - return null; + const [prevApi, setPrevApi] = useState(api); + if (prevApi !== api) { + setPrevApi(api); + void prevApi.cleanUp(); // https://github.com/silx-kit/h5web/pull/1568 } return {children};