diff --git a/client/refreshUtils.js b/client/refreshUtils.js index fdbbfee..6c1db7e 100644 --- a/client/refreshUtils.js +++ b/client/refreshUtils.js @@ -216,6 +216,9 @@ function executeRuntime(moduleExports, moduleId, hot, isTest) { let prevExports; if (isHotUpdate) { prevExports = hot.data.prevExports; + // `hot.data` stays reachable until this module is next disposed. Release the + // previous exports so that each version does not retain the one before it. + delete hot.data.prevExports; } if (isReactRefreshBoundary(moduleExports)) { diff --git a/test/refreshUtils.spec.ts b/test/refreshUtils.spec.ts index a04c5ec..fb094ce 100644 --- a/test/refreshUtils.spec.ts +++ b/test/refreshUtils.spec.ts @@ -1,9 +1,13 @@ import { performReactRefresh } from 'react-refresh/runtime'; import { rs } from 'rstack/test'; -import { enqueueUpdate } from '../client/refreshUtils.js'; +import { enqueueUpdate, executeRuntime } from '../client/refreshUtils.js'; rs.mock('react-refresh/runtime', () => ({ + getFamilyByType: (type: unknown) => + typeof type === 'function' ? type : undefined, + isLikelyComponentType: (type: unknown) => typeof type === 'function', performReactRefresh: rs.fn(), + register: () => {}, })); afterEach(() => { @@ -36,3 +40,54 @@ it.each([true, false])( expect(calls).toEqual([...expected, 'refresh']); }, ); + +it('releases the previous exports once a hot update has compared them', () => { + rs.useFakeTimers(); + const runVersion = ( + moduleExports: Record, + data?: Record, + ) => { + const disposeHandlers: Array<(data: Record) => void> = []; + const hot = { + data, + accept: () => {}, + dispose: (handler: (data: Record) => void) => { + disposeHandlers.push(handler); + }, + invalidate: rs.fn(), + }; + executeRuntime(moduleExports, 'module-id', hot); + const dispose = () => { + const nextData = {}; + for (const handler of disposeHandlers) { + handler(nextData); + } + return nextData; + }; + return { hot, dispose }; + }; + + const Component = () => null; + const firstExports = { default: Component }; + const first = runVersion(firstExports); + + // Same boundary signature: the update is accepted and the old exports are released. + const second = runVersion({ default: Component }, first.dispose()); + rs.advanceTimersByTime(30); + expect(second.hot.invalidate).not.toHaveBeenCalled(); + expect(performReactRefresh).toHaveBeenCalledTimes(1); + expect(second.hot.data).toEqual({}); + + // Changed boundary signature: the previous exports are compared, then released. + const third = runVersion( + { default: Component, Other: () => null }, + second.dispose(), + ); + expect(third.hot.invalidate).toHaveBeenCalledTimes(1); + expect(third.hot.data).toEqual({}); + + // No longer a boundary: the previous exports still invalidate, then are released. + const fourth = runVersion({ value: 1 }, third.dispose()); + expect(fourth.hot.invalidate).toHaveBeenCalledTimes(1); + expect(fourth.hot.data).toEqual({}); +});