Skip to content

Commit e0d106b

Browse files
authored
Leverage useId for internal fetcher keys when available (#11166)
1 parent d103537 commit e0d106b

File tree

3 files changed

+16
-3
lines changed

3 files changed

+16
-3
lines changed

.changeset/fetcher-key-useid.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"react-router-dom": patch
3+
---
4+
5+
Leverage `useId` for internal fetcher keys when available

packages/react-router-dom/__tests__/data-browser-router-test.tsx

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5368,9 +5368,11 @@ function testDomRouter(
53685368
{ window: getWindow("/") }
53695369
);
53705370
let { container } = render(<RouterProvider router={router} />);
5371-
expect(container.innerHTML).not.toMatch(/__\d+__,my-key/);
5371+
expect(container.innerHTML).not.toMatch(/my-key/);
53725372
await waitFor(() =>
5373-
expect(container.innerHTML).toMatch(/__\d+__,my-key/)
5373+
// React `useId()` results in either `:r2a:` or `:rp:` depending on
5374+
// `DataBrowserRouter`/`DataHashRouter`
5375+
expect(container.innerHTML).toMatch(/(:r2a:|:rp:),my-key/)
53745376
);
53755377
});
53765378
});

packages/react-router-dom/index.tsx

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -396,6 +396,8 @@ const START_TRANSITION = "startTransition";
396396
const startTransitionImpl = React[START_TRANSITION];
397397
const FLUSH_SYNC = "flushSync";
398398
const flushSyncImpl = ReactDOM[FLUSH_SYNC];
399+
const USE_ID = "useId";
400+
const useIdImpl = React[USE_ID];
399401

400402
function startTransitionSafe(cb: () => void) {
401403
if (startTransitionImpl) {
@@ -1634,10 +1636,14 @@ export function useFetcher<TData = any>({
16341636
);
16351637

16361638
// Fetcher key handling
1637-
let [fetcherKey, setFetcherKey] = React.useState<string>(key || "");
1639+
// OK to call conditionally to feature detect `useId`
1640+
// eslint-disable-next-line react-hooks/rules-of-hooks
1641+
let defaultKey = useIdImpl ? useIdImpl() : "";
1642+
let [fetcherKey, setFetcherKey] = React.useState<string>(key || defaultKey);
16381643
if (key && key !== fetcherKey) {
16391644
setFetcherKey(key);
16401645
} else if (!fetcherKey) {
1646+
// We will only fall through here when `useId` is not available
16411647
setFetcherKey(getUniqueFetcherId());
16421648
}
16431649

0 commit comments

Comments
 (0)