Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Memory leak suspense safe useId #7757

Merged
merged 6 commits into from
Feb 14, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 18 additions & 10 deletions packages/@react-aria/utils/src/useId.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,13 @@ let canUseDOM = Boolean(
window.document.createElement
);

let idsUpdaterMap: Map<string, Array<(v: string) => void>> = new Map();
export let idsUpdaterMap: Map<string, { current: string | null }[]> = new Map();
// This allows us to clean up the idsUpdaterMap when the id is no longer used.
// Map is a strong reference, so unused ids wouldn't be cleaned up otherwise.
// This can happen in suspended components where mount/unmount is not called.
let registry = new FinalizationRegistry<string>((heldValue) => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TIL

idsUpdaterMap.delete(heldValue);
});

/**
* If a default is not provided, generate an id.
Expand All @@ -33,23 +39,25 @@ export function useId(defaultId?: string): string {
let nextId = useRef(null);

let res = useSSRSafeId(value);
let cleanupRef = useRef(null);

let updateValue = useCallback((val) => {
nextId.current = val;
}, []);
registry.register(cleanupRef, res);

if (canUseDOM) {
// TS not smart enough to know that `has` means the value exists
if (idsUpdaterMap.has(res) && !idsUpdaterMap.get(res)!.includes(updateValue)) {
idsUpdaterMap.set(res, [...idsUpdaterMap.get(res)!, updateValue]);
const cacheIdRef = idsUpdaterMap.get(res);
if (cacheIdRef && !cacheIdRef.includes(nextId)) {
cacheIdRef.push(nextId);
} else {
idsUpdaterMap.set(res, [updateValue]);
idsUpdaterMap.set(res, [nextId]);
}
}

useLayoutEffect(() => {
let r = res;
return () => {
// In Suspense, the cleanup function may be not called
// when it is though, also remove it from the finalization registry.
registry.unregister(cleanupRef);
idsUpdaterMap.delete(r);
};
}, [res]);
Expand Down Expand Up @@ -79,13 +87,13 @@ export function mergeIds(idA: string, idB: string): string {

let setIdsA = idsUpdaterMap.get(idA);
if (setIdsA) {
setIdsA.forEach(fn => fn(idB));
setIdsA.forEach(ref => (ref.current = idB));
return idB;
}

let setIdsB = idsUpdaterMap.get(idB);
if (setIdsB) {
setIdsB.forEach(fn => fn(idA));
setIdsB.forEach((ref) => (ref.current = idA));
return idA;
}

Expand Down
76 changes: 76 additions & 0 deletions packages/@react-aria/utils/stories/useId.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/*
* Copyright 2025 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/

import {idsUpdaterMap} from '../src/useId';
import React, {Suspense, useState} from 'react';
import {useId} from '../';

export default {
title: 'useId'
};


let count = 0;
function AsyncComponent() {
if (count < 5) {
throw new Promise((resolve) => {
return setTimeout(() => {
console.log('resolving', count, Date.now());
count++;
resolve(true);
}, 100);
});
}

return null;
}

function TestUseId() {
let [show, setShow] = useState(true);
return (
<div>
{show && (
<Suspense>
<Box />
<AsyncComponent />
</Suspense>
)}
<button
onClick={() => {
count = 0;
setShow((prev) => !prev);
}}>toggle</button>
<button
onClick={() => {
console.log(idsUpdaterMap);
}}>See ids held</button>
</div>
);
}

function Box() {
const id = useId();
return (
<div data-id={id}>
{id}
</div>
);
}

export const GCuseId = {
render: () => <TestUseId />,
parameters: {
description: {
data: 'This story demonstrates garbage collection cleanup of useId hook. Depends on the browser when it happens. Easiest to see by rendering, clicking the toggle button twice, then waiting for the GC or, if you are in chrome, you can force GC to run with developer tools in the memory tab.'
}
}
};