Skip to content
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
5 changes: 5 additions & 0 deletions .changeset/custom-page-portal-stable-keys.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
---
'@clerk/react': patch
---

Keep custom pages and menu items mounted when sibling pages are added, removed, or reordered. Portals are now keyed by a stable id rather than their array index, so a surviving page is reconciled as an update instead of being remounted.
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
import { UserProfile } from '@clerk/react';
import { useContext } from 'react';
import { useContext, useState } from 'react';
import { PageContext, PageContextProvider } from '../PageContext.tsx';

function Page1() {
const { counter, setCounter } = useContext(PageContext);
// Local state lives INSIDE the portaled custom page. It only resets if the
// page is remounted, so it is our instrument for detecting remounts.
const [localCounter, setLocalCounter] = useState(0);

return (
<>
Expand All@@ -15,13 +18,31 @@ function Page1() {
>
Update
</button>
<p data-local-counter={1}>Local counter: {localCounter}</p>
<button
data-local-counter={1}
onClick={() => setLocalCounter(a => a + 1)}
>
Increment local
</button>
</>
);
}

export default function Page() {
// Bumping parent state recreates the <UserProfile> element, forcing the
// profile component (and useCustomPages) to rerender. The custom page content
// must survive this without remounting.
const [parentTick, setParentTick] = useState(0);

return (
<PageContextProvider>
<button
data-testid='rerender-parent'
onClick={() => setParentTick(t => t + 1)}
>
Rerender parent: {parentTick}
</button>
<UserProfile
fallback={<>Loading user profile</>}
path={'/custom-user-profile'}
Expand Down
31 changes: 31 additions & 0 deletions integration/tests/custom-pages.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -171,6 +171,37 @@ testAgainstRunningApps({ withPattern: ['react.vite.withEmailCodes'] })(
});
});

test('custom profile page survives a parent rerender without remounting', async ({ page, context }) => {
const u = createTestUtils({ app, page, context });
await u.po.signIn.goTo();
await u.po.signIn.waitForMounted();
await u.po.signIn.signInWithEmailAndInstantPassword({ email: fakeUser.email, password: fakeUser.password });
await u.po.expect.toBeSignedIn();

await u.page.goToRelative(CUSTOM_PROFILE_PAGE);
await u.po.userProfile.waitForMounted();

// Open the custom page (Page 1)
const [profilePage] = await u.page.locator('button.cl-navbarButton__custom-page-0').all();
await profilePage.click();

// Local state lives inside the portaled custom page and starts at 0.
await u.page.waitForSelector('p[data-local-counter="1"]', { state: 'attached' });
await expect(u.page.locator('p[data-local-counter="1"]')).toHaveText('Local counter: 0');

// Mutate the local state to 2.
await u.page.locator('button[data-local-counter="1"]').click();
await u.page.locator('button[data-local-counter="1"]').click();
await expect(u.page.locator('p[data-local-counter="1"]')).toHaveText('Local counter: 2');

// Force a parent rerender: this re-creates the <UserProfile> element and reruns useCustomPages.
await u.page.locator('button[data-testid="rerender-parent"]').click();
await expect(u.page.locator('button[data-testid="rerender-parent"]')).toHaveText('Rerender parent: 1');

// The custom page must NOT remount, so its local state is preserved.
await expect(u.page.locator('p[data-local-counter="1"]')).toHaveText('Local counter: 2');
});

test.describe('User Button with experimental asStandalone and asProvider', () => {
test('items at the specified order', async ({ page, context }) => {
const u = createTestUtils({ app, page, context });
Expand Down
4 changes: 2 additions & 2 deletions packages/react/src/components/uiComponents.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -127,8 +127,8 @@ type OrganizationSwitcherPropsWithoutCustomPages = Without<
const CustomPortalsRenderer = (props: CustomPortalsRendererProps) => {
return (
<>
{props?.customPagesPortals?.map((portal, index) => createElement(portal, { key: index }))}
{props?.customMenuItemsPortals?.map((portal, index) => createElement(portal, { key: index }))}
{props?.customPagesPortals?.map(({ key, portal }) => createElement(portal, { key }))}
{props?.customMenuItemsPortals?.map(({ key, portal }) => createElement(portal, { key }))}
</>
);
};
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
import { render, screen } from '@testing-library/react';
import React, { createElement, useEffect, useRef } from 'react';
import { afterEach, describe, expect, it, vi } from 'vitest';

import { OrganizationProfilePage } from '../../components/uiComponents';
import { useOrganizationProfileCustomPages } from '../useCustomPages';

vi.mock('@clerk/shared/utils', () => ({
logErrorInDevMode: vi.fn(),
}));

// Per-page mount/unmount counters. A remount re-runs the mount effect.
const mounts: Record<string, number> = {};
const unmounts: Record<string, number> = {};

// Stable component type, defined once. If it remounts across a rerender it is
// because the portal wrapping it changed identity or render key.
const TrackedContent = ({ id, text }: { id: string; text: string }) => {
useEffect(() => {
mounts[id] = (mounts[id] ?? 0) + 1;
return () => {
unmounts[id] = (unmounts[id] ?? 0) + 1;
};
// eslint-disable-next-line react-hooks/exhaustive-deps -- mount-once instrument; id is stable per instance
}, []);
return <div data-testid={`content-${id}`}>{text}</div>;
};

/**
* Faithfully reproduces the production render path for custom pages:
* - useOrganizationProfileCustomPages parses children into { customPages, customPagesPortals }
* - clerk-js calls customPages[i].mount(node) once per logical page (by identity; here keyed by url)
* - CustomPortalsRenderer renders each portal via createElement(portal, { key }) using the STABLE key
*/
const Harness = ({ children, tick }: { children: React.ReactNode; tick: number }) => {
const { customPages, customPagesPortals } = useOrganizationProfileCustomPages(children);
const hostRef = useRef<HTMLDivElement | null>(null);
const mountedUrls = useRef<Set<string>>(new Set());

useEffect(() => {
customPages.forEach(page => {
if (page.mount && page.url && !mountedUrls.current.has(page.url)) {
mountedUrls.current.add(page.url);
const node = document.createElement('div');
hostRef.current?.appendChild(node);
page.mount(node);
}
});
});

return (
<>
<div
data-tick={tick}
ref={hostRef}
/>
{customPagesPortals.map(({ key, portal }) => createElement(portal, { key }))}
</>
);
};

const makePage = (id: string, label: string, url: string, text: string) => (
<OrganizationProfilePage
key={id}
label={label}
labelIcon={<span>i</span>}
url={url}
>
<TrackedContent
id={id}
text={text}
/>
</OrganizationProfilePage>
);

afterEach(() => {
for (const k of Object.keys(mounts)) {
delete mounts[k];
}
for (const k of Object.keys(unmounts)) {
delete unmounts[k];
}
});

describe('custom pages remount behavior (integration through CustomPortalsRenderer path)', () => {
it('does not remount custom page content when the parent rerenders', async () => {
const { rerender } = render(<Harness tick={0}>{[makePage('p1', 'Page 1', 'page-1', 'first')]}</Harness>);

await screen.findByText('first');
expect(mounts['p1']).toBe(1);

// Parent rerenders for an unrelated reason; the page content prop changes but the
// logical page (key/label/url) is identical.
rerender(<Harness tick={1}>{[makePage('p1', 'Page 1', 'page-1', 'second')]}</Harness>);

await screen.findByText('second');
expect(mounts['p1']).toBe(1);
expect(unmounts['p1'] ?? 0).toBe(0);
});

it('does not remount a surviving custom page when another page is inserted before it', async () => {
const second = makePage('second', 'Second', 'second', 'second-content');
const first = makePage('first', 'First', 'first', 'first-content');

const { rerender } = render(<Harness tick={0}>{[second]}</Harness>);
await screen.findByText('second-content');
expect(mounts['second']).toBe(1);

// Insert a new page BEFORE the existing one.
rerender(<Harness tick={1}>{[first, second]}</Harness>);
await screen.findByText('first-content');

// The surviving page keeps its stable key + portal identity, so React reconciles it as an
// update rather than a remount.
expect(mounts['second']).toBe(1);
expect(unmounts['second'] ?? 0).toBe(0);
// The newly inserted page mounts exactly once.
expect(mounts['first']).toBe(1);
});
});
11 changes: 7 additions & 4 deletions packages/react/src/utils/__tests__/useCustomMenuItems.test.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -156,7 +156,8 @@ describe('useUserButtonCustomMenuItems', () => {

expect(result.current.customMenuItems).toHaveLength(2);
expect(result.current.customMenuItemsPortals).toHaveLength(2);
expect(result.current.customMenuItemsPortals[0]).not.toBe(result.current.customMenuItemsPortals[1]);
expect(result.current.customMenuItemsPortals[0].portal).not.toBe(result.current.customMenuItemsPortals[1].portal);
expect(result.current.customMenuItemsPortals[0].key).not.toBe(result.current.customMenuItemsPortals[1].key);
});

it('keeps portal identity with the logical menu item when inserting before it', () => {
Expand DownExpand Up@@ -187,12 +188,14 @@ describe('useUserButtonCustomMenuItems', () => {
},
);

const secondItemIconPortal = result.current.customMenuItemsPortals[0];
const secondItemIconPortal = result.current.customMenuItemsPortals[0].portal;
const secondItemIconKey = result.current.customMenuItemsPortals[0].key;

rerender({ includeFirstItem: true });

expect(result.current.customMenuItems).toHaveLength(2);
expect(result.current.customMenuItemsPortals[0]).not.toBe(secondItemIconPortal);
expect(result.current.customMenuItemsPortals[1]).toBe(secondItemIconPortal);
expect(result.current.customMenuItemsPortals[0].portal).not.toBe(secondItemIconPortal);
expect(result.current.customMenuItemsPortals[1].portal).toBe(secondItemIconPortal);
expect(result.current.customMenuItemsPortals[1].key).toBe(secondItemIconKey);
});
});
26 changes: 18 additions & 8 deletions packages/react/src/utils/__tests__/useCustomPages.test.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -36,8 +36,12 @@ describe('useOrganizationProfileCustomPages', () => {

expect(result.current.customPages).toHaveLength(2);
expect(result.current.customPagesPortals).toHaveLength(4);
expect(result.current.customPagesPortals[0]).not.toBe(result.current.customPagesPortals[2]);
expect(result.current.customPagesPortals[1]).not.toBe(result.current.customPagesPortals[3]);
// Duplicate (same label+url, no key) pages get distinct portal identities...
expect(result.current.customPagesPortals[0].portal).not.toBe(result.current.customPagesPortals[2].portal);
expect(result.current.customPagesPortals[1].portal).not.toBe(result.current.customPagesPortals[3].portal);
// ...and distinct stable render keys.
const keys = result.current.customPagesPortals.map(p => p.key);
expect(new Set(keys).size).toBe(keys.length);
});

it('keeps portal identity with the logical custom page when inserting before it', () => {
Expand DownExpand Up@@ -70,15 +74,21 @@ describe('useOrganizationProfileCustomPages', () => {
},
);

const secondPageContentPortal = result.current.customPagesPortals[0];
const secondPageIconPortal = result.current.customPagesPortals[1];
const secondPageContentPortal = result.current.customPagesPortals[0].portal;
const secondPageContentKey = result.current.customPagesPortals[0].key;
const secondPageIconPortal = result.current.customPagesPortals[1].portal;
const secondPageIconKey = result.current.customPagesPortals[1].key;

rerender({ includeFirstPage: true });

expect(result.current.customPages).toHaveLength(2);
expect(result.current.customPagesPortals[0]).not.toBe(secondPageContentPortal);
expect(result.current.customPagesPortals[1]).not.toBe(secondPageIconPortal);
expect(result.current.customPagesPortals[2]).toBe(secondPageContentPortal);
expect(result.current.customPagesPortals[3]).toBe(secondPageIconPortal);
expect(result.current.customPagesPortals[0].portal).not.toBe(secondPageContentPortal);
expect(result.current.customPagesPortals[1].portal).not.toBe(secondPageIconPortal);
// The second page keeps BOTH its portal identity and its stable render key when it moves
// position, so CustomPortalsRenderer reconciles it as an update instead of a remount.
expect(result.current.customPagesPortals[2].portal).toBe(secondPageContentPortal);
expect(result.current.customPagesPortals[2].key).toBe(secondPageContentKey);
expect(result.current.customPagesPortals[3].portal).toBe(secondPageIconPortal);
expect(result.current.customPagesPortals[3].key).toBe(secondPageIconKey);
});
});
6 changes: 3 additions & 3 deletions packages/react/src/utils/useCustomMenuItems.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -57,7 +57,7 @@ const useCustomMenuItems = ({
}: UseCustomMenuItemsParams) => {
const validChildren: CustomMenuItemType[] = [];
const customMenuItems: CustomMenuItem[] = [];
const customMenuItemsPortals: React.ComponentType[] = [];
const customMenuItemsPortals: Array<{ key: string; portal: React.ComponentType }> = [];
const portalIdCounts = new Map<string, number>();

React.Children.forEach(children, child => {
Expand DownExpand Up@@ -181,7 +181,7 @@ const useCustomMenuItems = ({
menuItem.open = mi.open;
}
customMenuItems.push(menuItem);
customMenuItemsPortals.push(iconPortal);
customMenuItemsPortals.push({ key: `icon:${mi.portalId || index}`, portal: iconPortal });
}
if (isExternalLink(mi)) {
const {
Expand All@@ -195,7 +195,7 @@ const useCustomMenuItems = ({
mountIcon,
unmountIcon,
});
customMenuItemsPortals.push(iconPortal);
customMenuItemsPortals.push({ key: `icon:${mi.portalId || index}`, portal: iconPortal });
}
});

Expand Down
8 changes: 4 additions & 4 deletions packages/react/src/utils/useCustomPages.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -179,7 +179,7 @@ const useCustomPages = (params: UseCustomPagesParams, options?: UseCustomPagesOp
const customLinkLabelIconsPortals = useCustomElementPortal(customLinkLabelIcons);

const customPages: CustomPage[] = [];
const customPagesPortals: React.ComponentType[] = [];
const customPagesPortals: Array<{ key: string; portal: React.ComponentType }> = [];

validChildren.forEach((cp, index) => {
if (isReorderItem(cp, reorderItemsLabels)) {
Expand All@@ -198,8 +198,8 @@ const useCustomPages = (params: UseCustomPagesParams, options?: UseCustomPagesOp
unmount: unmountIcon,
} = customPageLabelIconsPortals.find(p => p.id === (cp.portalId || index)) as UseCustomElementPortalReturn;
customPages.push({ label: cp.label, url: cp.url, mount, unmount, mountIcon, unmountIcon });
customPagesPortals.push(contentPortal);
customPagesPortals.push(labelPortal);
customPagesPortals.push({ key: `content:${cp.portalId || index}`, portal: contentPortal });
customPagesPortals.push({ key: `label:${cp.portalId || index}`, portal: labelPortal });
return;
}
if (isExternalLink(cp)) {
Expand All@@ -209,7 +209,7 @@ const useCustomPages = (params: UseCustomPagesParams, options?: UseCustomPagesOp
unmount: unmountIcon,
} = customLinkLabelIconsPortals.find(p => p.id === (cp.portalId || index)) as UseCustomElementPortalReturn;
customPages.push({ label: cp.label, url: cp.url, mountIcon, unmountIcon });
customPagesPortals.push(labelPortal);
customPagesPortals.push({ key: `label:${cp.portalId || index}`, portal: labelPortal });
return;
}
});
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
fix(react): key custom page portals by stable id by jacekradko · Pull Request #8730 · clerk/javascript · GitHub
Skip to content
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
5 changes: 5 additions & 0 deletions .changeset/custom-page-portal-stable-keys.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
---
'@clerk/react': patch
---

Keep custom pages and menu items mounted when sibling pages are added, removed, or reordered. Portals are now keyed by a stable id rather than their array index, so a surviving page is reconciled as an update instead of being remounted.
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
import { UserProfile } from '@clerk/react';
import { useContext } from 'react';
import { useContext, useState } from 'react';
import { PageContext, PageContextProvider } from '../PageContext.tsx';

function Page1() {
const { counter, setCounter } = useContext(PageContext);
// Local state lives INSIDE the portaled custom page. It only resets if the
// page is remounted, so it is our instrument for detecting remounts.
const [localCounter, setLocalCounter] = useState(0);

return (
<>
Expand All@@ -15,13 +18,31 @@ function Page1() {
>
Update
</button>
<p data-local-counter={1}>Local counter: {localCounter}</p>
<button
data-local-counter={1}
onClick={() => setLocalCounter(a => a + 1)}
>
Increment local
</button>
</>
);
}

export default function Page() {
// Bumping parent state recreates the <UserProfile> element, forcing the
// profile component (and useCustomPages) to rerender. The custom page content
// must survive this without remounting.
const [parentTick, setParentTick] = useState(0);

return (
<PageContextProvider>
<button
data-testid='rerender-parent'
onClick={() => setParentTick(t => t + 1)}
>
Rerender parent: {parentTick}
</button>
<UserProfile
fallback={<>Loading user profile</>}
path={'/custom-user-profile'}
Expand Down
31 changes: 31 additions & 0 deletions integration/tests/custom-pages.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -171,6 +171,37 @@ testAgainstRunningApps({ withPattern: ['react.vite.withEmailCodes'] })(
});
});

test('custom profile page survives a parent rerender without remounting', async ({ page, context }) => {
const u = createTestUtils({ app, page, context });
await u.po.signIn.goTo();
await u.po.signIn.waitForMounted();
await u.po.signIn.signInWithEmailAndInstantPassword({ email: fakeUser.email, password: fakeUser.password });
await u.po.expect.toBeSignedIn();

await u.page.goToRelative(CUSTOM_PROFILE_PAGE);
await u.po.userProfile.waitForMounted();

// Open the custom page (Page 1)
const [profilePage] = await u.page.locator('button.cl-navbarButton__custom-page-0').all();
await profilePage.click();

// Local state lives inside the portaled custom page and starts at 0.
await u.page.waitForSelector('p[data-local-counter="1"]', { state: 'attached' });
await expect(u.page.locator('p[data-local-counter="1"]')).toHaveText('Local counter: 0');

// Mutate the local state to 2.
await u.page.locator('button[data-local-counter="1"]').click();
await u.page.locator('button[data-local-counter="1"]').click();
await expect(u.page.locator('p[data-local-counter="1"]')).toHaveText('Local counter: 2');

// Force a parent rerender: this re-creates the <UserProfile> element and reruns useCustomPages.
await u.page.locator('button[data-testid="rerender-parent"]').click();
await expect(u.page.locator('button[data-testid="rerender-parent"]')).toHaveText('Rerender parent: 1');

// The custom page must NOT remount, so its local state is preserved.
await expect(u.page.locator('p[data-local-counter="1"]')).toHaveText('Local counter: 2');
});

test.describe('User Button with experimental asStandalone and asProvider', () => {
test('items at the specified order', async ({ page, context }) => {
const u = createTestUtils({ app, page, context });
Expand Down
4 changes: 2 additions & 2 deletions packages/react/src/components/uiComponents.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -127,8 +127,8 @@ type OrganizationSwitcherPropsWithoutCustomPages = Without<
const CustomPortalsRenderer = (props: CustomPortalsRendererProps) => {
return (
<>
{props?.customPagesPortals?.map((portal, index) => createElement(portal, { key: index }))}
{props?.customMenuItemsPortals?.map((portal, index) => createElement(portal, { key: index }))}
{props?.customPagesPortals?.map(({ key, portal }) => createElement(portal, { key }))}
{props?.customMenuItemsPortals?.map(({ key, portal }) => createElement(portal, { key }))}
</>
);
};
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
import { render, screen } from '@testing-library/react';
import React, { createElement, useEffect, useRef } from 'react';
import { afterEach, describe, expect, it, vi } from 'vitest';

import { OrganizationProfilePage } from '../../components/uiComponents';
import { useOrganizationProfileCustomPages } from '../useCustomPages';

vi.mock('@clerk/shared/utils', () => ({
logErrorInDevMode: vi.fn(),
}));

// Per-page mount/unmount counters. A remount re-runs the mount effect.
const mounts: Record<string, number> = {};
const unmounts: Record<string, number> = {};

// Stable component type, defined once. If it remounts across a rerender it is
// because the portal wrapping it changed identity or render key.
const TrackedContent = ({ id, text }: { id: string; text: string }) => {
useEffect(() => {
mounts[id] = (mounts[id] ?? 0) + 1;
return () => {
unmounts[id] = (unmounts[id] ?? 0) + 1;
};
// eslint-disable-next-line react-hooks/exhaustive-deps -- mount-once instrument; id is stable per instance
}, []);
return <div data-testid={`content-${id}`}>{text}</div>;
};

/**
* Faithfully reproduces the production render path for custom pages:
* - useOrganizationProfileCustomPages parses children into { customPages, customPagesPortals }
* - clerk-js calls customPages[i].mount(node) once per logical page (by identity; here keyed by url)
* - CustomPortalsRenderer renders each portal via createElement(portal, { key }) using the STABLE key
*/
const Harness = ({ children, tick }: { children: React.ReactNode; tick: number }) => {
const { customPages, customPagesPortals } = useOrganizationProfileCustomPages(children);
const hostRef = useRef<HTMLDivElement | null>(null);
const mountedUrls = useRef<Set<string>>(new Set());

useEffect(() => {
customPages.forEach(page => {
if (page.mount && page.url && !mountedUrls.current.has(page.url)) {
mountedUrls.current.add(page.url);
const node = document.createElement('div');
hostRef.current?.appendChild(node);
page.mount(node);
}
});
});

return (
<>
<div
data-tick={tick}
ref={hostRef}
/>
{customPagesPortals.map(({ key, portal }) => createElement(portal, { key }))}
</>
);
};

const makePage = (id: string, label: string, url: string, text: string) => (
<OrganizationProfilePage
key={id}
label={label}
labelIcon={<span>i</span>}
url={url}
>
<TrackedContent
id={id}
text={text}
/>
</OrganizationProfilePage>
);

afterEach(() => {
for (const k of Object.keys(mounts)) {
delete mounts[k];
}
for (const k of Object.keys(unmounts)) {
delete unmounts[k];
}
});

describe('custom pages remount behavior (integration through CustomPortalsRenderer path)', () => {
it('does not remount custom page content when the parent rerenders', async () => {
const { rerender } = render(<Harness tick={0}>{[makePage('p1', 'Page 1', 'page-1', 'first')]}</Harness>);

await screen.findByText('first');
expect(mounts['p1']).toBe(1);

// Parent rerenders for an unrelated reason; the page content prop changes but the
// logical page (key/label/url) is identical.
rerender(<Harness tick={1}>{[makePage('p1', 'Page 1', 'page-1', 'second')]}</Harness>);

await screen.findByText('second');
expect(mounts['p1']).toBe(1);
expect(unmounts['p1'] ?? 0).toBe(0);
});

it('does not remount a surviving custom page when another page is inserted before it', async () => {
const second = makePage('second', 'Second', 'second', 'second-content');
const first = makePage('first', 'First', 'first', 'first-content');

const { rerender } = render(<Harness tick={0}>{[second]}</Harness>);
await screen.findByText('second-content');
expect(mounts['second']).toBe(1);

// Insert a new page BEFORE the existing one.
rerender(<Harness tick={1}>{[first, second]}</Harness>);
await screen.findByText('first-content');

// The surviving page keeps its stable key + portal identity, so React reconciles it as an
// update rather than a remount.
expect(mounts['second']).toBe(1);
expect(unmounts['second'] ?? 0).toBe(0);
// The newly inserted page mounts exactly once.
expect(mounts['first']).toBe(1);
});
});
11 changes: 7 additions & 4 deletions packages/react/src/utils/__tests__/useCustomMenuItems.test.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -156,7 +156,8 @@ describe('useUserButtonCustomMenuItems', () => {

expect(result.current.customMenuItems).toHaveLength(2);
expect(result.current.customMenuItemsPortals).toHaveLength(2);
expect(result.current.customMenuItemsPortals[0]).not.toBe(result.current.customMenuItemsPortals[1]);
expect(result.current.customMenuItemsPortals[0].portal).not.toBe(result.current.customMenuItemsPortals[1].portal);
expect(result.current.customMenuItemsPortals[0].key).not.toBe(result.current.customMenuItemsPortals[1].key);
});

it('keeps portal identity with the logical menu item when inserting before it', () => {
Expand DownExpand Up@@ -187,12 +188,14 @@ describe('useUserButtonCustomMenuItems', () => {
},
);

const secondItemIconPortal = result.current.customMenuItemsPortals[0];
const secondItemIconPortal = result.current.customMenuItemsPortals[0].portal;
const secondItemIconKey = result.current.customMenuItemsPortals[0].key;

rerender({ includeFirstItem: true });

expect(result.current.customMenuItems).toHaveLength(2);
expect(result.current.customMenuItemsPortals[0]).not.toBe(secondItemIconPortal);
expect(result.current.customMenuItemsPortals[1]).toBe(secondItemIconPortal);
expect(result.current.customMenuItemsPortals[0].portal).not.toBe(secondItemIconPortal);
expect(result.current.customMenuItemsPortals[1].portal).toBe(secondItemIconPortal);
expect(result.current.customMenuItemsPortals[1].key).toBe(secondItemIconKey);
});
});
26 changes: 18 additions & 8 deletions packages/react/src/utils/__tests__/useCustomPages.test.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -36,8 +36,12 @@ describe('useOrganizationProfileCustomPages', () => {

expect(result.current.customPages).toHaveLength(2);
expect(result.current.customPagesPortals).toHaveLength(4);
expect(result.current.customPagesPortals[0]).not.toBe(result.current.customPagesPortals[2]);
expect(result.current.customPagesPortals[1]).not.toBe(result.current.customPagesPortals[3]);
// Duplicate (same label+url, no key) pages get distinct portal identities...
expect(result.current.customPagesPortals[0].portal).not.toBe(result.current.customPagesPortals[2].portal);
expect(result.current.customPagesPortals[1].portal).not.toBe(result.current.customPagesPortals[3].portal);
// ...and distinct stable render keys.
const keys = result.current.customPagesPortals.map(p => p.key);
expect(new Set(keys).size).toBe(keys.length);
});

it('keeps portal identity with the logical custom page when inserting before it', () => {
Expand DownExpand Up@@ -70,15 +74,21 @@ describe('useOrganizationProfileCustomPages', () => {
},
);

const secondPageContentPortal = result.current.customPagesPortals[0];
const secondPageIconPortal = result.current.customPagesPortals[1];
const secondPageContentPortal = result.current.customPagesPortals[0].portal;
const secondPageContentKey = result.current.customPagesPortals[0].key;
const secondPageIconPortal = result.current.customPagesPortals[1].portal;
const secondPageIconKey = result.current.customPagesPortals[1].key;

rerender({ includeFirstPage: true });

expect(result.current.customPages).toHaveLength(2);
expect(result.current.customPagesPortals[0]).not.toBe(secondPageContentPortal);
expect(result.current.customPagesPortals[1]).not.toBe(secondPageIconPortal);
expect(result.current.customPagesPortals[2]).toBe(secondPageContentPortal);
expect(result.current.customPagesPortals[3]).toBe(secondPageIconPortal);
expect(result.current.customPagesPortals[0].portal).not.toBe(secondPageContentPortal);
expect(result.current.customPagesPortals[1].portal).not.toBe(secondPageIconPortal);
// The second page keeps BOTH its portal identity and its stable render key when it moves
// position, so CustomPortalsRenderer reconciles it as an update instead of a remount.
expect(result.current.customPagesPortals[2].portal).toBe(secondPageContentPortal);
expect(result.current.customPagesPortals[2].key).toBe(secondPageContentKey);
expect(result.current.customPagesPortals[3].portal).toBe(secondPageIconPortal);
expect(result.current.customPagesPortals[3].key).toBe(secondPageIconKey);
});
});
6 changes: 3 additions & 3 deletions packages/react/src/utils/useCustomMenuItems.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -57,7 +57,7 @@ const useCustomMenuItems = ({
}: UseCustomMenuItemsParams) => {
const validChildren: CustomMenuItemType[] = [];
const customMenuItems: CustomMenuItem[] = [];
const customMenuItemsPortals: React.ComponentType[] = [];
const customMenuItemsPortals: Array<{ key: string; portal: React.ComponentType }> = [];
const portalIdCounts = new Map<string, number>();

React.Children.forEach(children, child => {
Expand DownExpand Up@@ -181,7 +181,7 @@ const useCustomMenuItems = ({
menuItem.open = mi.open;
}
customMenuItems.push(menuItem);
customMenuItemsPortals.push(iconPortal);
customMenuItemsPortals.push({ key: `icon:${mi.portalId || index}`, portal: iconPortal });
}
if (isExternalLink(mi)) {
const {
Expand All@@ -195,7 +195,7 @@ const useCustomMenuItems = ({
mountIcon,
unmountIcon,
});
customMenuItemsPortals.push(iconPortal);
customMenuItemsPortals.push({ key: `icon:${mi.portalId || index}`, portal: iconPortal });
}
});

Expand Down
8 changes: 4 additions & 4 deletions packages/react/src/utils/useCustomPages.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -179,7 +179,7 @@ const useCustomPages = (params: UseCustomPagesParams, options?: UseCustomPagesOp
const customLinkLabelIconsPortals = useCustomElementPortal(customLinkLabelIcons);

const customPages: CustomPage[] = [];
const customPagesPortals: React.ComponentType[] = [];
const customPagesPortals: Array<{ key: string; portal: React.ComponentType }> = [];

validChildren.forEach((cp, index) => {
if (isReorderItem(cp, reorderItemsLabels)) {
Expand All@@ -198,8 +198,8 @@ const useCustomPages = (params: UseCustomPagesParams, options?: UseCustomPagesOp
unmount: unmountIcon,
} = customPageLabelIconsPortals.find(p => p.id === (cp.portalId || index)) as UseCustomElementPortalReturn;
customPages.push({ label: cp.label, url: cp.url, mount, unmount, mountIcon, unmountIcon });
customPagesPortals.push(contentPortal);
customPagesPortals.push(labelPortal);
customPagesPortals.push({ key: `content:${cp.portalId || index}`, portal: contentPortal });
customPagesPortals.push({ key: `label:${cp.portalId || index}`, portal: labelPortal });
return;
}
if (isExternalLink(cp)) {
Expand All@@ -209,7 +209,7 @@ const useCustomPages = (params: UseCustomPagesParams, options?: UseCustomPagesOp
unmount: unmountIcon,
} = customLinkLabelIconsPortals.find(p => p.id === (cp.portalId || index)) as UseCustomElementPortalReturn;
customPages.push({ label: cp.label, url: cp.url, mountIcon, unmountIcon });
customPagesPortals.push(labelPortal);
customPagesPortals.push({ key: `label:${cp.portalId || index}`, portal: labelPortal });
return;
}
});
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' fix(react): key custom page portals by stable id by jacekradko · Pull Request #8730 · clerk/javascript · GitHub
Skip to content
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
5 changes: 5 additions & 0 deletions .changeset/custom-page-portal-stable-keys.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
---
'@clerk/react': patch
---

Keep custom pages and menu items mounted when sibling pages are added, removed, or reordered. Portals are now keyed by a stable id rather than their array index, so a surviving page is reconciled as an update instead of being remounted.
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
import { UserProfile } from '@clerk/react';
import { useContext } from 'react';
import { useContext, useState } from 'react';
import { PageContext, PageContextProvider } from '../PageContext.tsx';

function Page1() {
const { counter, setCounter } = useContext(PageContext);
// Local state lives INSIDE the portaled custom page. It only resets if the
// page is remounted, so it is our instrument for detecting remounts.
const [localCounter, setLocalCounter] = useState(0);

return (
<>
Expand All@@ -15,13 +18,31 @@ function Page1() {
>
Update
</button>
<p data-local-counter={1}>Local counter: {localCounter}</p>
<button
data-local-counter={1}
onClick={() => setLocalCounter(a => a + 1)}
>
Increment local
</button>
</>
);
}

export default function Page() {
// Bumping parent state recreates the <UserProfile> element, forcing the
// profile component (and useCustomPages) to rerender. The custom page content
// must survive this without remounting.
const [parentTick, setParentTick] = useState(0);

return (
<PageContextProvider>
<button
data-testid='rerender-parent'
onClick={() => setParentTick(t => t + 1)}
>
Rerender parent: {parentTick}
</button>
<UserProfile
fallback={<>Loading user profile</>}
path={'/custom-user-profile'}
Expand Down
31 changes: 31 additions & 0 deletions integration/tests/custom-pages.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -171,6 +171,37 @@ testAgainstRunningApps({ withPattern: ['react.vite.withEmailCodes'] })(
});
});

test('custom profile page survives a parent rerender without remounting', async ({ page, context }) => {
const u = createTestUtils({ app, page, context });
await u.po.signIn.goTo();
await u.po.signIn.waitForMounted();
await u.po.signIn.signInWithEmailAndInstantPassword({ email: fakeUser.email, password: fakeUser.password });
await u.po.expect.toBeSignedIn();

await u.page.goToRelative(CUSTOM_PROFILE_PAGE);
await u.po.userProfile.waitForMounted();

// Open the custom page (Page 1)
const [profilePage] = await u.page.locator('button.cl-navbarButton__custom-page-0').all();
await profilePage.click();

// Local state lives inside the portaled custom page and starts at 0.
await u.page.waitForSelector('p[data-local-counter="1"]', { state: 'attached' });
await expect(u.page.locator('p[data-local-counter="1"]')).toHaveText('Local counter: 0');

// Mutate the local state to 2.
await u.page.locator('button[data-local-counter="1"]').click();
await u.page.locator('button[data-local-counter="1"]').click();
await expect(u.page.locator('p[data-local-counter="1"]')).toHaveText('Local counter: 2');

// Force a parent rerender: this re-creates the <UserProfile> element and reruns useCustomPages.
await u.page.locator('button[data-testid="rerender-parent"]').click();
await expect(u.page.locator('button[data-testid="rerender-parent"]')).toHaveText('Rerender parent: 1');

// The custom page must NOT remount, so its local state is preserved.
await expect(u.page.locator('p[data-local-counter="1"]')).toHaveText('Local counter: 2');
});

test.describe('User Button with experimental asStandalone and asProvider', () => {
test('items at the specified order', async ({ page, context }) => {
const u = createTestUtils({ app, page, context });
Expand Down
4 changes: 2 additions & 2 deletions packages/react/src/components/uiComponents.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -127,8 +127,8 @@ type OrganizationSwitcherPropsWithoutCustomPages = Without<
const CustomPortalsRenderer = (props: CustomPortalsRendererProps) => {
return (
<>
{props?.customPagesPortals?.map((portal, index) => createElement(portal, { key: index }))}
{props?.customMenuItemsPortals?.map((portal, index) => createElement(portal, { key: index }))}
{props?.customPagesPortals?.map(({ key, portal }) => createElement(portal, { key }))}
{props?.customMenuItemsPortals?.map(({ key, portal }) => createElement(portal, { key }))}
</>
);
};
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
import { render, screen } from '@testing-library/react';
import React, { createElement, useEffect, useRef } from 'react';
import { afterEach, describe, expect, it, vi } from 'vitest';

import { OrganizationProfilePage } from '../../components/uiComponents';
import { useOrganizationProfileCustomPages } from '../useCustomPages';

vi.mock('@clerk/shared/utils', () => ({
logErrorInDevMode: vi.fn(),
}));

// Per-page mount/unmount counters. A remount re-runs the mount effect.
const mounts: Record<string, number> = {};
const unmounts: Record<string, number> = {};

// Stable component type, defined once. If it remounts across a rerender it is
// because the portal wrapping it changed identity or render key.
const TrackedContent = ({ id, text }: { id: string; text: string }) => {
useEffect(() => {
mounts[id] = (mounts[id] ?? 0) + 1;
return () => {
unmounts[id] = (unmounts[id] ?? 0) + 1;
};
// eslint-disable-next-line react-hooks/exhaustive-deps -- mount-once instrument; id is stable per instance
}, []);
return <div data-testid={`content-${id}`}>{text}</div>;
};

/**
* Faithfully reproduces the production render path for custom pages:
* - useOrganizationProfileCustomPages parses children into { customPages, customPagesPortals }
* - clerk-js calls customPages[i].mount(node) once per logical page (by identity; here keyed by url)
* - CustomPortalsRenderer renders each portal via createElement(portal, { key }) using the STABLE key
*/
const Harness = ({ children, tick }: { children: React.ReactNode; tick: number }) => {
const { customPages, customPagesPortals } = useOrganizationProfileCustomPages(children);
const hostRef = useRef<HTMLDivElement | null>(null);
const mountedUrls = useRef<Set<string>>(new Set());

useEffect(() => {
customPages.forEach(page => {
if (page.mount && page.url && !mountedUrls.current.has(page.url)) {
mountedUrls.current.add(page.url);
const node = document.createElement('div');
hostRef.current?.appendChild(node);
page.mount(node);
}
});
});

return (
<>
<div
data-tick={tick}
ref={hostRef}
/>
{customPagesPortals.map(({ key, portal }) => createElement(portal, { key }))}
</>
);
};

const makePage = (id: string, label: string, url: string, text: string) => (
<OrganizationProfilePage
key={id}
label={label}
labelIcon={<span>i</span>}
url={url}
>
<TrackedContent
id={id}
text={text}
/>
</OrganizationProfilePage>
);

afterEach(() => {
for (const k of Object.keys(mounts)) {
delete mounts[k];
}
for (const k of Object.keys(unmounts)) {
delete unmounts[k];
}
});

describe('custom pages remount behavior (integration through CustomPortalsRenderer path)', () => {
it('does not remount custom page content when the parent rerenders', async () => {
const { rerender } = render(<Harness tick={0}>{[makePage('p1', 'Page 1', 'page-1', 'first')]}</Harness>);

await screen.findByText('first');
expect(mounts['p1']).toBe(1);

// Parent rerenders for an unrelated reason; the page content prop changes but the
// logical page (key/label/url) is identical.
rerender(<Harness tick={1}>{[makePage('p1', 'Page 1', 'page-1', 'second')]}</Harness>);

await screen.findByText('second');
expect(mounts['p1']).toBe(1);
expect(unmounts['p1'] ?? 0).toBe(0);
});

it('does not remount a surviving custom page when another page is inserted before it', async () => {
const second = makePage('second', 'Second', 'second', 'second-content');
const first = makePage('first', 'First', 'first', 'first-content');

const { rerender } = render(<Harness tick={0}>{[second]}</Harness>);
await screen.findByText('second-content');
expect(mounts['second']).toBe(1);

// Insert a new page BEFORE the existing one.
rerender(<Harness tick={1}>{[first, second]}</Harness>);
await screen.findByText('first-content');

// The surviving page keeps its stable key + portal identity, so React reconciles it as an
// update rather than a remount.
expect(mounts['second']).toBe(1);
expect(unmounts['second'] ?? 0).toBe(0);
// The newly inserted page mounts exactly once.
expect(mounts['first']).toBe(1);
});
});
11 changes: 7 additions & 4 deletions packages/react/src/utils/__tests__/useCustomMenuItems.test.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -156,7 +156,8 @@ describe('useUserButtonCustomMenuItems', () => {

expect(result.current.customMenuItems).toHaveLength(2);
expect(result.current.customMenuItemsPortals).toHaveLength(2);
expect(result.current.customMenuItemsPortals[0]).not.toBe(result.current.customMenuItemsPortals[1]);
expect(result.current.customMenuItemsPortals[0].portal).not.toBe(result.current.customMenuItemsPortals[1].portal);
expect(result.current.customMenuItemsPortals[0].key).not.toBe(result.current.customMenuItemsPortals[1].key);
});

it('keeps portal identity with the logical menu item when inserting before it', () => {
Expand DownExpand Up@@ -187,12 +188,14 @@ describe('useUserButtonCustomMenuItems', () => {
},
);

const secondItemIconPortal = result.current.customMenuItemsPortals[0];
const secondItemIconPortal = result.current.customMenuItemsPortals[0].portal;
const secondItemIconKey = result.current.customMenuItemsPortals[0].key;

rerender({ includeFirstItem: true });

expect(result.current.customMenuItems).toHaveLength(2);
expect(result.current.customMenuItemsPortals[0]).not.toBe(secondItemIconPortal);
expect(result.current.customMenuItemsPortals[1]).toBe(secondItemIconPortal);
expect(result.current.customMenuItemsPortals[0].portal).not.toBe(secondItemIconPortal);
expect(result.current.customMenuItemsPortals[1].portal).toBe(secondItemIconPortal);
expect(result.current.customMenuItemsPortals[1].key).toBe(secondItemIconKey);
});
});
26 changes: 18 additions & 8 deletions packages/react/src/utils/__tests__/useCustomPages.test.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -36,8 +36,12 @@ describe('useOrganizationProfileCustomPages', () => {

expect(result.current.customPages).toHaveLength(2);
expect(result.current.customPagesPortals).toHaveLength(4);
expect(result.current.customPagesPortals[0]).not.toBe(result.current.customPagesPortals[2]);
expect(result.current.customPagesPortals[1]).not.toBe(result.current.customPagesPortals[3]);
// Duplicate (same label+url, no key) pages get distinct portal identities...
expect(result.current.customPagesPortals[0].portal).not.toBe(result.current.customPagesPortals[2].portal);
expect(result.current.customPagesPortals[1].portal).not.toBe(result.current.customPagesPortals[3].portal);
// ...and distinct stable render keys.
const keys = result.current.customPagesPortals.map(p => p.key);
expect(new Set(keys).size).toBe(keys.length);
});

it('keeps portal identity with the logical custom page when inserting before it', () => {
Expand DownExpand Up@@ -70,15 +74,21 @@ describe('useOrganizationProfileCustomPages', () => {
},
);

const secondPageContentPortal = result.current.customPagesPortals[0];
const secondPageIconPortal = result.current.customPagesPortals[1];
const secondPageContentPortal = result.current.customPagesPortals[0].portal;
const secondPageContentKey = result.current.customPagesPortals[0].key;
const secondPageIconPortal = result.current.customPagesPortals[1].portal;
const secondPageIconKey = result.current.customPagesPortals[1].key;

rerender({ includeFirstPage: true });

expect(result.current.customPages).toHaveLength(2);
expect(result.current.customPagesPortals[0]).not.toBe(secondPageContentPortal);
expect(result.current.customPagesPortals[1]).not.toBe(secondPageIconPortal);
expect(result.current.customPagesPortals[2]).toBe(secondPageContentPortal);
expect(result.current.customPagesPortals[3]).toBe(secondPageIconPortal);
expect(result.current.customPagesPortals[0].portal).not.toBe(secondPageContentPortal);
expect(result.current.customPagesPortals[1].portal).not.toBe(secondPageIconPortal);
// The second page keeps BOTH its portal identity and its stable render key when it moves
// position, so CustomPortalsRenderer reconciles it as an update instead of a remount.
expect(result.current.customPagesPortals[2].portal).toBe(secondPageContentPortal);
expect(result.current.customPagesPortals[2].key).toBe(secondPageContentKey);
expect(result.current.customPagesPortals[3].portal).toBe(secondPageIconPortal);
expect(result.current.customPagesPortals[3].key).toBe(secondPageIconKey);
});
});
6 changes: 3 additions & 3 deletions packages/react/src/utils/useCustomMenuItems.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -57,7 +57,7 @@ const useCustomMenuItems = ({
}: UseCustomMenuItemsParams) => {
const validChildren: CustomMenuItemType[] = [];
const customMenuItems: CustomMenuItem[] = [];
const customMenuItemsPortals: React.ComponentType[] = [];
const customMenuItemsPortals: Array<{ key: string; portal: React.ComponentType }> = [];
const portalIdCounts = new Map<string, number>();

React.Children.forEach(children, child => {
Expand DownExpand Up@@ -181,7 +181,7 @@ const useCustomMenuItems = ({
menuItem.open = mi.open;
}
customMenuItems.push(menuItem);
customMenuItemsPortals.push(iconPortal);
customMenuItemsPortals.push({ key: `icon:${mi.portalId || index}`, portal: iconPortal });
}
if (isExternalLink(mi)) {
const {
Expand All@@ -195,7 +195,7 @@ const useCustomMenuItems = ({
mountIcon,
unmountIcon,
});
customMenuItemsPortals.push(iconPortal);
customMenuItemsPortals.push({ key: `icon:${mi.portalId || index}`, portal: iconPortal });
}
});

Expand Down
8 changes: 4 additions & 4 deletions packages/react/src/utils/useCustomPages.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -179,7 +179,7 @@ const useCustomPages = (params: UseCustomPagesParams, options?: UseCustomPagesOp
const customLinkLabelIconsPortals = useCustomElementPortal(customLinkLabelIcons);

const customPages: CustomPage[] = [];
const customPagesPortals: React.ComponentType[] = [];
const customPagesPortals: Array<{ key: string; portal: React.ComponentType }> = [];

validChildren.forEach((cp, index) => {
if (isReorderItem(cp, reorderItemsLabels)) {
Expand All@@ -198,8 +198,8 @@ const useCustomPages = (params: UseCustomPagesParams, options?: UseCustomPagesOp
unmount: unmountIcon,
} = customPageLabelIconsPortals.find(p => p.id === (cp.portalId || index)) as UseCustomElementPortalReturn;
customPages.push({ label: cp.label, url: cp.url, mount, unmount, mountIcon, unmountIcon });
customPagesPortals.push(contentPortal);
customPagesPortals.push(labelPortal);
customPagesPortals.push({ key: `content:${cp.portalId || index}`, portal: contentPortal });
customPagesPortals.push({ key: `label:${cp.portalId || index}`, portal: labelPortal });
return;
}
if (isExternalLink(cp)) {
Expand All@@ -209,7 +209,7 @@ const useCustomPages = (params: UseCustomPagesParams, options?: UseCustomPagesOp
unmount: unmountIcon,
} = customLinkLabelIconsPortals.find(p => p.id === (cp.portalId || index)) as UseCustomElementPortalReturn;
customPages.push({ label: cp.label, url: cp.url, mountIcon, unmountIcon });
customPagesPortals.push(labelPortal);
customPagesPortals.push({ key: `label:${cp.portalId || index}`, portal: labelPortal });
return;
}
});
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' fix(react): key custom page portals by stable id by jacekradko · Pull Request #8730 · clerk/javascript · GitHub
Skip to content
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
5 changes: 5 additions & 0 deletions .changeset/custom-page-portal-stable-keys.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
---
'@clerk/react': patch
---

Keep custom pages and menu items mounted when sibling pages are added, removed, or reordered. Portals are now keyed by a stable id rather than their array index, so a surviving page is reconciled as an update instead of being remounted.
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
import { UserProfile } from '@clerk/react';
import { useContext } from 'react';
import { useContext, useState } from 'react';
import { PageContext, PageContextProvider } from '../PageContext.tsx';

function Page1() {
const { counter, setCounter } = useContext(PageContext);
// Local state lives INSIDE the portaled custom page. It only resets if the
// page is remounted, so it is our instrument for detecting remounts.
const [localCounter, setLocalCounter] = useState(0);

return (
<>
Expand All@@ -15,13 +18,31 @@ function Page1() {
>
Update
</button>
<p data-local-counter={1}>Local counter: {localCounter}</p>
<button
data-local-counter={1}
onClick={() => setLocalCounter(a => a + 1)}
>
Increment local
</button>
</>
);
}

export default function Page() {
// Bumping parent state recreates the <UserProfile> element, forcing the
// profile component (and useCustomPages) to rerender. The custom page content
// must survive this without remounting.
const [parentTick, setParentTick] = useState(0);

return (
<PageContextProvider>
<button
data-testid='rerender-parent'
onClick={() => setParentTick(t => t + 1)}
>
Rerender parent: {parentTick}
</button>
<UserProfile
fallback={<>Loading user profile</>}
path={'/custom-user-profile'}
Expand Down
31 changes: 31 additions & 0 deletions integration/tests/custom-pages.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -171,6 +171,37 @@ testAgainstRunningApps({ withPattern: ['react.vite.withEmailCodes'] })(
});
});

test('custom profile page survives a parent rerender without remounting', async ({ page, context }) => {
const u = createTestUtils({ app, page, context });
await u.po.signIn.goTo();
await u.po.signIn.waitForMounted();
await u.po.signIn.signInWithEmailAndInstantPassword({ email: fakeUser.email, password: fakeUser.password });
await u.po.expect.toBeSignedIn();

await u.page.goToRelative(CUSTOM_PROFILE_PAGE);
await u.po.userProfile.waitForMounted();

// Open the custom page (Page 1)
const [profilePage] = await u.page.locator('button.cl-navbarButton__custom-page-0').all();
await profilePage.click();

// Local state lives inside the portaled custom page and starts at 0.
await u.page.waitForSelector('p[data-local-counter="1"]', { state: 'attached' });
await expect(u.page.locator('p[data-local-counter="1"]')).toHaveText('Local counter: 0');

// Mutate the local state to 2.
await u.page.locator('button[data-local-counter="1"]').click();
await u.page.locator('button[data-local-counter="1"]').click();
await expect(u.page.locator('p[data-local-counter="1"]')).toHaveText('Local counter: 2');

// Force a parent rerender: this re-creates the <UserProfile> element and reruns useCustomPages.
await u.page.locator('button[data-testid="rerender-parent"]').click();
await expect(u.page.locator('button[data-testid="rerender-parent"]')).toHaveText('Rerender parent: 1');

// The custom page must NOT remount, so its local state is preserved.
await expect(u.page.locator('p[data-local-counter="1"]')).toHaveText('Local counter: 2');
});

test.describe('User Button with experimental asStandalone and asProvider', () => {
test('items at the specified order', async ({ page, context }) => {
const u = createTestUtils({ app, page, context });
Expand Down
4 changes: 2 additions & 2 deletions packages/react/src/components/uiComponents.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -127,8 +127,8 @@ type OrganizationSwitcherPropsWithoutCustomPages = Without<
const CustomPortalsRenderer = (props: CustomPortalsRendererProps) => {
return (
<>
{props?.customPagesPortals?.map((portal, index) => createElement(portal, { key: index }))}
{props?.customMenuItemsPortals?.map((portal, index) => createElement(portal, { key: index }))}
{props?.customPagesPortals?.map(({ key, portal }) => createElement(portal, { key }))}
{props?.customMenuItemsPortals?.map(({ key, portal }) => createElement(portal, { key }))}
</>
);
};
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
import { render, screen } from '@testing-library/react';
import React, { createElement, useEffect, useRef } from 'react';
import { afterEach, describe, expect, it, vi } from 'vitest';

import { OrganizationProfilePage } from '../../components/uiComponents';
import { useOrganizationProfileCustomPages } from '../useCustomPages';

vi.mock('@clerk/shared/utils', () => ({
logErrorInDevMode: vi.fn(),
}));

// Per-page mount/unmount counters. A remount re-runs the mount effect.
const mounts: Record<string, number> = {};
const unmounts: Record<string, number> = {};

// Stable component type, defined once. If it remounts across a rerender it is
// because the portal wrapping it changed identity or render key.
const TrackedContent = ({ id, text }: { id: string; text: string }) => {
useEffect(() => {
mounts[id] = (mounts[id] ?? 0) + 1;
return () => {
unmounts[id] = (unmounts[id] ?? 0) + 1;
};
// eslint-disable-next-line react-hooks/exhaustive-deps -- mount-once instrument; id is stable per instance
}, []);
return <div data-testid={`content-${id}`}>{text}</div>;
};

/**
* Faithfully reproduces the production render path for custom pages:
* - useOrganizationProfileCustomPages parses children into { customPages, customPagesPortals }
* - clerk-js calls customPages[i].mount(node) once per logical page (by identity; here keyed by url)
* - CustomPortalsRenderer renders each portal via createElement(portal, { key }) using the STABLE key
*/
const Harness = ({ children, tick }: { children: React.ReactNode; tick: number }) => {
const { customPages, customPagesPortals } = useOrganizationProfileCustomPages(children);
const hostRef = useRef<HTMLDivElement | null>(null);
const mountedUrls = useRef<Set<string>>(new Set());

useEffect(() => {
customPages.forEach(page => {
if (page.mount && page.url && !mountedUrls.current.has(page.url)) {
mountedUrls.current.add(page.url);
const node = document.createElement('div');
hostRef.current?.appendChild(node);
page.mount(node);
}
});
});

return (
<>
<div
data-tick={tick}
ref={hostRef}
/>
{customPagesPortals.map(({ key, portal }) => createElement(portal, { key }))}
</>
);
};

const makePage = (id: string, label: string, url: string, text: string) => (
<OrganizationProfilePage
key={id}
label={label}
labelIcon={<span>i</span>}
url={url}
>
<TrackedContent
id={id}
text={text}
/>
</OrganizationProfilePage>
);

afterEach(() => {
for (const k of Object.keys(mounts)) {
delete mounts[k];
}
for (const k of Object.keys(unmounts)) {
delete unmounts[k];
}
});

describe('custom pages remount behavior (integration through CustomPortalsRenderer path)', () => {
it('does not remount custom page content when the parent rerenders', async () => {
const { rerender } = render(<Harness tick={0}>{[makePage('p1', 'Page 1', 'page-1', 'first')]}</Harness>);

await screen.findByText('first');
expect(mounts['p1']).toBe(1);

// Parent rerenders for an unrelated reason; the page content prop changes but the
// logical page (key/label/url) is identical.
rerender(<Harness tick={1}>{[makePage('p1', 'Page 1', 'page-1', 'second')]}</Harness>);

await screen.findByText('second');
expect(mounts['p1']).toBe(1);
expect(unmounts['p1'] ?? 0).toBe(0);
});

it('does not remount a surviving custom page when another page is inserted before it', async () => {
const second = makePage('second', 'Second', 'second', 'second-content');
const first = makePage('first', 'First', 'first', 'first-content');

const { rerender } = render(<Harness tick={0}>{[second]}</Harness>);
await screen.findByText('second-content');
expect(mounts['second']).toBe(1);

// Insert a new page BEFORE the existing one.
rerender(<Harness tick={1}>{[first, second]}</Harness>);
await screen.findByText('first-content');

// The surviving page keeps its stable key + portal identity, so React reconciles it as an
// update rather than a remount.
expect(mounts['second']).toBe(1);
expect(unmounts['second'] ?? 0).toBe(0);
// The newly inserted page mounts exactly once.
expect(mounts['first']).toBe(1);
});
});
11 changes: 7 additions & 4 deletions packages/react/src/utils/__tests__/useCustomMenuItems.test.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -156,7 +156,8 @@ describe('useUserButtonCustomMenuItems', () => {

expect(result.current.customMenuItems).toHaveLength(2);
expect(result.current.customMenuItemsPortals).toHaveLength(2);
expect(result.current.customMenuItemsPortals[0]).not.toBe(result.current.customMenuItemsPortals[1]);
expect(result.current.customMenuItemsPortals[0].portal).not.toBe(result.current.customMenuItemsPortals[1].portal);
expect(result.current.customMenuItemsPortals[0].key).not.toBe(result.current.customMenuItemsPortals[1].key);
});

it('keeps portal identity with the logical menu item when inserting before it', () => {
Expand DownExpand Up@@ -187,12 +188,14 @@ describe('useUserButtonCustomMenuItems', () => {
},
);

const secondItemIconPortal = result.current.customMenuItemsPortals[0];
const secondItemIconPortal = result.current.customMenuItemsPortals[0].portal;
const secondItemIconKey = result.current.customMenuItemsPortals[0].key;

rerender({ includeFirstItem: true });

expect(result.current.customMenuItems).toHaveLength(2);
expect(result.current.customMenuItemsPortals[0]).not.toBe(secondItemIconPortal);
expect(result.current.customMenuItemsPortals[1]).toBe(secondItemIconPortal);
expect(result.current.customMenuItemsPortals[0].portal).not.toBe(secondItemIconPortal);
expect(result.current.customMenuItemsPortals[1].portal).toBe(secondItemIconPortal);
expect(result.current.customMenuItemsPortals[1].key).toBe(secondItemIconKey);
});
});
26 changes: 18 additions & 8 deletions packages/react/src/utils/__tests__/useCustomPages.test.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -36,8 +36,12 @@ describe('useOrganizationProfileCustomPages', () => {

expect(result.current.customPages).toHaveLength(2);
expect(result.current.customPagesPortals).toHaveLength(4);
expect(result.current.customPagesPortals[0]).not.toBe(result.current.customPagesPortals[2]);
expect(result.current.customPagesPortals[1]).not.toBe(result.current.customPagesPortals[3]);
// Duplicate (same label+url, no key) pages get distinct portal identities...
expect(result.current.customPagesPortals[0].portal).not.toBe(result.current.customPagesPortals[2].portal);
expect(result.current.customPagesPortals[1].portal).not.toBe(result.current.customPagesPortals[3].portal);
// ...and distinct stable render keys.
const keys = result.current.customPagesPortals.map(p => p.key);
expect(new Set(keys).size).toBe(keys.length);
});

it('keeps portal identity with the logical custom page when inserting before it', () => {
Expand DownExpand Up@@ -70,15 +74,21 @@ describe('useOrganizationProfileCustomPages', () => {
},
);

const secondPageContentPortal = result.current.customPagesPortals[0];
const secondPageIconPortal = result.current.customPagesPortals[1];
const secondPageContentPortal = result.current.customPagesPortals[0].portal;
const secondPageContentKey = result.current.customPagesPortals[0].key;
const secondPageIconPortal = result.current.customPagesPortals[1].portal;
const secondPageIconKey = result.current.customPagesPortals[1].key;

rerender({ includeFirstPage: true });

expect(result.current.customPages).toHaveLength(2);
expect(result.current.customPagesPortals[0]).not.toBe(secondPageContentPortal);
expect(result.current.customPagesPortals[1]).not.toBe(secondPageIconPortal);
expect(result.current.customPagesPortals[2]).toBe(secondPageContentPortal);
expect(result.current.customPagesPortals[3]).toBe(secondPageIconPortal);
expect(result.current.customPagesPortals[0].portal).not.toBe(secondPageContentPortal);
expect(result.current.customPagesPortals[1].portal).not.toBe(secondPageIconPortal);
// The second page keeps BOTH its portal identity and its stable render key when it moves
// position, so CustomPortalsRenderer reconciles it as an update instead of a remount.
expect(result.current.customPagesPortals[2].portal).toBe(secondPageContentPortal);
expect(result.current.customPagesPortals[2].key).toBe(secondPageContentKey);
expect(result.current.customPagesPortals[3].portal).toBe(secondPageIconPortal);
expect(result.current.customPagesPortals[3].key).toBe(secondPageIconKey);
});
});
6 changes: 3 additions & 3 deletions packages/react/src/utils/useCustomMenuItems.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -57,7 +57,7 @@ const useCustomMenuItems = ({
}: UseCustomMenuItemsParams) => {
const validChildren: CustomMenuItemType[] = [];
const customMenuItems: CustomMenuItem[] = [];
const customMenuItemsPortals: React.ComponentType[] = [];
const customMenuItemsPortals: Array<{ key: string; portal: React.ComponentType }> = [];
const portalIdCounts = new Map<string, number>();

React.Children.forEach(children, child => {
Expand DownExpand Up@@ -181,7 +181,7 @@ const useCustomMenuItems = ({
menuItem.open = mi.open;
}
customMenuItems.push(menuItem);
customMenuItemsPortals.push(iconPortal);
customMenuItemsPortals.push({ key: `icon:${mi.portalId || index}`, portal: iconPortal });
}
if (isExternalLink(mi)) {
const {
Expand All@@ -195,7 +195,7 @@ const useCustomMenuItems = ({
mountIcon,
unmountIcon,
});
customMenuItemsPortals.push(iconPortal);
customMenuItemsPortals.push({ key: `icon:${mi.portalId || index}`, portal: iconPortal });
}
});

Expand Down
8 changes: 4 additions & 4 deletions packages/react/src/utils/useCustomPages.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -179,7 +179,7 @@ const useCustomPages = (params: UseCustomPagesParams, options?: UseCustomPagesOp
const customLinkLabelIconsPortals = useCustomElementPortal(customLinkLabelIcons);

const customPages: CustomPage[] = [];
const customPagesPortals: React.ComponentType[] = [];
const customPagesPortals: Array<{ key: string; portal: React.ComponentType }> = [];

validChildren.forEach((cp, index) => {
if (isReorderItem(cp, reorderItemsLabels)) {
Expand All@@ -198,8 +198,8 @@ const useCustomPages = (params: UseCustomPagesParams, options?: UseCustomPagesOp
unmount: unmountIcon,
} = customPageLabelIconsPortals.find(p => p.id === (cp.portalId || index)) as UseCustomElementPortalReturn;
customPages.push({ label: cp.label, url: cp.url, mount, unmount, mountIcon, unmountIcon });
customPagesPortals.push(contentPortal);
customPagesPortals.push(labelPortal);
customPagesPortals.push({ key: `content:${cp.portalId || index}`, portal: contentPortal });
customPagesPortals.push({ key: `label:${cp.portalId || index}`, portal: labelPortal });
return;
}
if (isExternalLink(cp)) {
Expand All@@ -209,7 +209,7 @@ const useCustomPages = (params: UseCustomPagesParams, options?: UseCustomPagesOp
unmount: unmountIcon,
} = customLinkLabelIconsPortals.find(p => p.id === (cp.portalId || index)) as UseCustomElementPortalReturn;
customPages.push({ label: cp.label, url: cp.url, mountIcon, unmountIcon });
customPagesPortals.push(labelPortal);
customPagesPortals.push({ key: `label:${cp.portalId || index}`, portal: labelPortal });
return;
}
});
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' fix(react): key custom page portals by stable id by jacekradko · Pull Request #8730 · clerk/javascript · GitHub
Skip to content
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
5 changes: 5 additions & 0 deletions .changeset/custom-page-portal-stable-keys.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
---
'@clerk/react': patch
---

Keep custom pages and menu items mounted when sibling pages are added, removed, or reordered. Portals are now keyed by a stable id rather than their array index, so a surviving page is reconciled as an update instead of being remounted.
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
import { UserProfile } from '@clerk/react';
import { useContext } from 'react';
import { useContext, useState } from 'react';
import { PageContext, PageContextProvider } from '../PageContext.tsx';

function Page1() {
const { counter, setCounter } = useContext(PageContext);
// Local state lives INSIDE the portaled custom page. It only resets if the
// page is remounted, so it is our instrument for detecting remounts.
const [localCounter, setLocalCounter] = useState(0);

return (
<>
Expand All@@ -15,13 +18,31 @@ function Page1() {
>
Update
</button>
<p data-local-counter={1}>Local counter: {localCounter}</p>
<button
data-local-counter={1}
onClick={() => setLocalCounter(a => a + 1)}
>
Increment local
</button>
</>
);
}

export default function Page() {
// Bumping parent state recreates the <UserProfile> element, forcing the
// profile component (and useCustomPages) to rerender. The custom page content
// must survive this without remounting.
const [parentTick, setParentTick] = useState(0);

return (
<PageContextProvider>
<button
data-testid='rerender-parent'
onClick={() => setParentTick(t => t + 1)}
>
Rerender parent: {parentTick}
</button>
<UserProfile
fallback={<>Loading user profile</>}
path={'/custom-user-profile'}
Expand Down
31 changes: 31 additions & 0 deletions integration/tests/custom-pages.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -171,6 +171,37 @@ testAgainstRunningApps({ withPattern: ['react.vite.withEmailCodes'] })(
});
});

test('custom profile page survives a parent rerender without remounting', async ({ page, context }) => {
const u = createTestUtils({ app, page, context });
await u.po.signIn.goTo();
await u.po.signIn.waitForMounted();
await u.po.signIn.signInWithEmailAndInstantPassword({ email: fakeUser.email, password: fakeUser.password });
await u.po.expect.toBeSignedIn();

await u.page.goToRelative(CUSTOM_PROFILE_PAGE);
await u.po.userProfile.waitForMounted();

// Open the custom page (Page 1)
const [profilePage] = await u.page.locator('button.cl-navbarButton__custom-page-0').all();
await profilePage.click();

// Local state lives inside the portaled custom page and starts at 0.
await u.page.waitForSelector('p[data-local-counter="1"]', { state: 'attached' });
await expect(u.page.locator('p[data-local-counter="1"]')).toHaveText('Local counter: 0');

// Mutate the local state to 2.
await u.page.locator('button[data-local-counter="1"]').click();
await u.page.locator('button[data-local-counter="1"]').click();
await expect(u.page.locator('p[data-local-counter="1"]')).toHaveText('Local counter: 2');

// Force a parent rerender: this re-creates the <UserProfile> element and reruns useCustomPages.
await u.page.locator('button[data-testid="rerender-parent"]').click();
await expect(u.page.locator('button[data-testid="rerender-parent"]')).toHaveText('Rerender parent: 1');

// The custom page must NOT remount, so its local state is preserved.
await expect(u.page.locator('p[data-local-counter="1"]')).toHaveText('Local counter: 2');
});

test.describe('User Button with experimental asStandalone and asProvider', () => {
test('items at the specified order', async ({ page, context }) => {
const u = createTestUtils({ app, page, context });
Expand Down
4 changes: 2 additions & 2 deletions packages/react/src/components/uiComponents.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -127,8 +127,8 @@ type OrganizationSwitcherPropsWithoutCustomPages = Without<
const CustomPortalsRenderer = (props: CustomPortalsRendererProps) => {
return (
<>
{props?.customPagesPortals?.map((portal, index) => createElement(portal, { key: index }))}
{props?.customMenuItemsPortals?.map((portal, index) => createElement(portal, { key: index }))}
{props?.customPagesPortals?.map(({ key, portal }) => createElement(portal, { key }))}
{props?.customMenuItemsPortals?.map(({ key, portal }) => createElement(portal, { key }))}
</>
);
};
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
import { render, screen } from '@testing-library/react';
import React, { createElement, useEffect, useRef } from 'react';
import { afterEach, describe, expect, it, vi } from 'vitest';

import { OrganizationProfilePage } from '../../components/uiComponents';
import { useOrganizationProfileCustomPages } from '../useCustomPages';

vi.mock('@clerk/shared/utils', () => ({
logErrorInDevMode: vi.fn(),
}));

// Per-page mount/unmount counters. A remount re-runs the mount effect.
const mounts: Record<string, number> = {};
const unmounts: Record<string, number> = {};

// Stable component type, defined once. If it remounts across a rerender it is
// because the portal wrapping it changed identity or render key.
const TrackedContent = ({ id, text }: { id: string; text: string }) => {
useEffect(() => {
mounts[id] = (mounts[id] ?? 0) + 1;
return () => {
unmounts[id] = (unmounts[id] ?? 0) + 1;
};
// eslint-disable-next-line react-hooks/exhaustive-deps -- mount-once instrument; id is stable per instance
}, []);
return <div data-testid={`content-${id}`}>{text}</div>;
};

/**
* Faithfully reproduces the production render path for custom pages:
* - useOrganizationProfileCustomPages parses children into { customPages, customPagesPortals }
* - clerk-js calls customPages[i].mount(node) once per logical page (by identity; here keyed by url)
* - CustomPortalsRenderer renders each portal via createElement(portal, { key }) using the STABLE key
*/
const Harness = ({ children, tick }: { children: React.ReactNode; tick: number }) => {
const { customPages, customPagesPortals } = useOrganizationProfileCustomPages(children);
const hostRef = useRef<HTMLDivElement | null>(null);
const mountedUrls = useRef<Set<string>>(new Set());

useEffect(() => {
customPages.forEach(page => {
if (page.mount && page.url && !mountedUrls.current.has(page.url)) {
mountedUrls.current.add(page.url);
const node = document.createElement('div');
hostRef.current?.appendChild(node);
page.mount(node);
}
});
});

return (
<>
<div
data-tick={tick}
ref={hostRef}
/>
{customPagesPortals.map(({ key, portal }) => createElement(portal, { key }))}
</>
);
};

const makePage = (id: string, label: string, url: string, text: string) => (
<OrganizationProfilePage
key={id}
label={label}
labelIcon={<span>i</span>}
url={url}
>
<TrackedContent
id={id}
text={text}
/>
</OrganizationProfilePage>
);

afterEach(() => {
for (const k of Object.keys(mounts)) {
delete mounts[k];
}
for (const k of Object.keys(unmounts)) {
delete unmounts[k];
}
});

describe('custom pages remount behavior (integration through CustomPortalsRenderer path)', () => {
it('does not remount custom page content when the parent rerenders', async () => {
const { rerender } = render(<Harness tick={0}>{[makePage('p1', 'Page 1', 'page-1', 'first')]}</Harness>);

await screen.findByText('first');
expect(mounts['p1']).toBe(1);

// Parent rerenders for an unrelated reason; the page content prop changes but the
// logical page (key/label/url) is identical.
rerender(<Harness tick={1}>{[makePage('p1', 'Page 1', 'page-1', 'second')]}</Harness>);

await screen.findByText('second');
expect(mounts['p1']).toBe(1);
expect(unmounts['p1'] ?? 0).toBe(0);
});

it('does not remount a surviving custom page when another page is inserted before it', async () => {
const second = makePage('second', 'Second', 'second', 'second-content');
const first = makePage('first', 'First', 'first', 'first-content');

const { rerender } = render(<Harness tick={0}>{[second]}</Harness>);
await screen.findByText('second-content');
expect(mounts['second']).toBe(1);

// Insert a new page BEFORE the existing one.
rerender(<Harness tick={1}>{[first, second]}</Harness>);
await screen.findByText('first-content');

// The surviving page keeps its stable key + portal identity, so React reconciles it as an
// update rather than a remount.
expect(mounts['second']).toBe(1);
expect(unmounts['second'] ?? 0).toBe(0);
// The newly inserted page mounts exactly once.
expect(mounts['first']).toBe(1);
});
});
11 changes: 7 additions & 4 deletions packages/react/src/utils/__tests__/useCustomMenuItems.test.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -156,7 +156,8 @@ describe('useUserButtonCustomMenuItems', () => {

expect(result.current.customMenuItems).toHaveLength(2);
expect(result.current.customMenuItemsPortals).toHaveLength(2);
expect(result.current.customMenuItemsPortals[0]).not.toBe(result.current.customMenuItemsPortals[1]);
expect(result.current.customMenuItemsPortals[0].portal).not.toBe(result.current.customMenuItemsPortals[1].portal);
expect(result.current.customMenuItemsPortals[0].key).not.toBe(result.current.customMenuItemsPortals[1].key);
});

it('keeps portal identity with the logical menu item when inserting before it', () => {
Expand DownExpand Up@@ -187,12 +188,14 @@ describe('useUserButtonCustomMenuItems', () => {
},
);

const secondItemIconPortal = result.current.customMenuItemsPortals[0];
const secondItemIconPortal = result.current.customMenuItemsPortals[0].portal;
const secondItemIconKey = result.current.customMenuItemsPortals[0].key;

rerender({ includeFirstItem: true });

expect(result.current.customMenuItems).toHaveLength(2);
expect(result.current.customMenuItemsPortals[0]).not.toBe(secondItemIconPortal);
expect(result.current.customMenuItemsPortals[1]).toBe(secondItemIconPortal);
expect(result.current.customMenuItemsPortals[0].portal).not.toBe(secondItemIconPortal);
expect(result.current.customMenuItemsPortals[1].portal).toBe(secondItemIconPortal);
expect(result.current.customMenuItemsPortals[1].key).toBe(secondItemIconKey);
});
});
26 changes: 18 additions & 8 deletions packages/react/src/utils/__tests__/useCustomPages.test.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -36,8 +36,12 @@ describe('useOrganizationProfileCustomPages', () => {

expect(result.current.customPages).toHaveLength(2);
expect(result.current.customPagesPortals).toHaveLength(4);
expect(result.current.customPagesPortals[0]).not.toBe(result.current.customPagesPortals[2]);
expect(result.current.customPagesPortals[1]).not.toBe(result.current.customPagesPortals[3]);
// Duplicate (same label+url, no key) pages get distinct portal identities...
expect(result.current.customPagesPortals[0].portal).not.toBe(result.current.customPagesPortals[2].portal);
expect(result.current.customPagesPortals[1].portal).not.toBe(result.current.customPagesPortals[3].portal);
// ...and distinct stable render keys.
const keys = result.current.customPagesPortals.map(p => p.key);
expect(new Set(keys).size).toBe(keys.length);
});

it('keeps portal identity with the logical custom page when inserting before it', () => {
Expand DownExpand Up@@ -70,15 +74,21 @@ describe('useOrganizationProfileCustomPages', () => {
},
);

const secondPageContentPortal = result.current.customPagesPortals[0];
const secondPageIconPortal = result.current.customPagesPortals[1];
const secondPageContentPortal = result.current.customPagesPortals[0].portal;
const secondPageContentKey = result.current.customPagesPortals[0].key;
const secondPageIconPortal = result.current.customPagesPortals[1].portal;
const secondPageIconKey = result.current.customPagesPortals[1].key;

rerender({ includeFirstPage: true });

expect(result.current.customPages).toHaveLength(2);
expect(result.current.customPagesPortals[0]).not.toBe(secondPageContentPortal);
expect(result.current.customPagesPortals[1]).not.toBe(secondPageIconPortal);
expect(result.current.customPagesPortals[2]).toBe(secondPageContentPortal);
expect(result.current.customPagesPortals[3]).toBe(secondPageIconPortal);
expect(result.current.customPagesPortals[0].portal).not.toBe(secondPageContentPortal);
expect(result.current.customPagesPortals[1].portal).not.toBe(secondPageIconPortal);
// The second page keeps BOTH its portal identity and its stable render key when it moves
// position, so CustomPortalsRenderer reconciles it as an update instead of a remount.
expect(result.current.customPagesPortals[2].portal).toBe(secondPageContentPortal);
expect(result.current.customPagesPortals[2].key).toBe(secondPageContentKey);
expect(result.current.customPagesPortals[3].portal).toBe(secondPageIconPortal);
expect(result.current.customPagesPortals[3].key).toBe(secondPageIconKey);
});
});
6 changes: 3 additions & 3 deletions packages/react/src/utils/useCustomMenuItems.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -57,7 +57,7 @@ const useCustomMenuItems = ({
}: UseCustomMenuItemsParams) => {
const validChildren: CustomMenuItemType[] = [];
const customMenuItems: CustomMenuItem[] = [];
const customMenuItemsPortals: React.ComponentType[] = [];
const customMenuItemsPortals: Array<{ key: string; portal: React.ComponentType }> = [];
const portalIdCounts = new Map<string, number>();

React.Children.forEach(children, child => {
Expand DownExpand Up@@ -181,7 +181,7 @@ const useCustomMenuItems = ({
menuItem.open = mi.open;
}
customMenuItems.push(menuItem);
customMenuItemsPortals.push(iconPortal);
customMenuItemsPortals.push({ key: `icon:${mi.portalId || index}`, portal: iconPortal });
}
if (isExternalLink(mi)) {
const {
Expand All@@ -195,7 +195,7 @@ const useCustomMenuItems = ({
mountIcon,
unmountIcon,
});
customMenuItemsPortals.push(iconPortal);
customMenuItemsPortals.push({ key: `icon:${mi.portalId || index}`, portal: iconPortal });
}
});

Expand Down
8 changes: 4 additions & 4 deletions packages/react/src/utils/useCustomPages.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -179,7 +179,7 @@ const useCustomPages = (params: UseCustomPagesParams, options?: UseCustomPagesOp
const customLinkLabelIconsPortals = useCustomElementPortal(customLinkLabelIcons);

const customPages: CustomPage[] = [];
const customPagesPortals: React.ComponentType[] = [];
const customPagesPortals: Array<{ key: string; portal: React.ComponentType }> = [];

validChildren.forEach((cp, index) => {
if (isReorderItem(cp, reorderItemsLabels)) {
Expand All@@ -198,8 +198,8 @@ const useCustomPages = (params: UseCustomPagesParams, options?: UseCustomPagesOp
unmount: unmountIcon,
} = customPageLabelIconsPortals.find(p => p.id === (cp.portalId || index)) as UseCustomElementPortalReturn;
customPages.push({ label: cp.label, url: cp.url, mount, unmount, mountIcon, unmountIcon });
customPagesPortals.push(contentPortal);
customPagesPortals.push(labelPortal);
customPagesPortals.push({ key: `content:${cp.portalId || index}`, portal: contentPortal });
customPagesPortals.push({ key: `label:${cp.portalId || index}`, portal: labelPortal });
return;
}
if (isExternalLink(cp)) {
Expand All@@ -209,7 +209,7 @@ const useCustomPages = (params: UseCustomPagesParams, options?: UseCustomPagesOp
unmount: unmountIcon,
} = customLinkLabelIconsPortals.find(p => p.id === (cp.portalId || index)) as UseCustomElementPortalReturn;
customPages.push({ label: cp.label, url: cp.url, mountIcon, unmountIcon });
customPagesPortals.push(labelPortal);
customPagesPortals.push({ key: `label:${cp.portalId || index}`, portal: labelPortal });
return;
}
});
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' fix(react): key custom page portals by stable id by jacekradko · Pull Request #8730 · clerk/javascript · GitHub
Skip to content
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
5 changes: 5 additions & 0 deletions .changeset/custom-page-portal-stable-keys.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
---
'@clerk/react': patch
---

Keep custom pages and menu items mounted when sibling pages are added, removed, or reordered. Portals are now keyed by a stable id rather than their array index, so a surviving page is reconciled as an update instead of being remounted.
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
import { UserProfile } from '@clerk/react';
import { useContext } from 'react';
import { useContext, useState } from 'react';
import { PageContext, PageContextProvider } from '../PageContext.tsx';

function Page1() {
const { counter, setCounter } = useContext(PageContext);
// Local state lives INSIDE the portaled custom page. It only resets if the
// page is remounted, so it is our instrument for detecting remounts.
const [localCounter, setLocalCounter] = useState(0);

return (
<>
Expand All@@ -15,13 +18,31 @@ function Page1() {
>
Update
</button>
<p data-local-counter={1}>Local counter: {localCounter}</p>
<button
data-local-counter={1}
onClick={() => setLocalCounter(a => a + 1)}
>
Increment local
</button>
</>
);
}

export default function Page() {
// Bumping parent state recreates the <UserProfile> element, forcing the
// profile component (and useCustomPages) to rerender. The custom page content
// must survive this without remounting.
const [parentTick, setParentTick] = useState(0);

return (
<PageContextProvider>
<button
data-testid='rerender-parent'
onClick={() => setParentTick(t => t + 1)}
>
Rerender parent: {parentTick}
</button>
<UserProfile
fallback={<>Loading user profile</>}
path={'/custom-user-profile'}
Expand Down
31 changes: 31 additions & 0 deletions integration/tests/custom-pages.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -171,6 +171,37 @@ testAgainstRunningApps({ withPattern: ['react.vite.withEmailCodes'] })(
});
});

test('custom profile page survives a parent rerender without remounting', async ({ page, context }) => {
const u = createTestUtils({ app, page, context });
await u.po.signIn.goTo();
await u.po.signIn.waitForMounted();
await u.po.signIn.signInWithEmailAndInstantPassword({ email: fakeUser.email, password: fakeUser.password });
await u.po.expect.toBeSignedIn();

await u.page.goToRelative(CUSTOM_PROFILE_PAGE);
await u.po.userProfile.waitForMounted();

// Open the custom page (Page 1)
const [profilePage] = await u.page.locator('button.cl-navbarButton__custom-page-0').all();
await profilePage.click();

// Local state lives inside the portaled custom page and starts at 0.
await u.page.waitForSelector('p[data-local-counter="1"]', { state: 'attached' });
await expect(u.page.locator('p[data-local-counter="1"]')).toHaveText('Local counter: 0');

// Mutate the local state to 2.
await u.page.locator('button[data-local-counter="1"]').click();
await u.page.locator('button[data-local-counter="1"]').click();
await expect(u.page.locator('p[data-local-counter="1"]')).toHaveText('Local counter: 2');

// Force a parent rerender: this re-creates the <UserProfile> element and reruns useCustomPages.
await u.page.locator('button[data-testid="rerender-parent"]').click();
await expect(u.page.locator('button[data-testid="rerender-parent"]')).toHaveText('Rerender parent: 1');

// The custom page must NOT remount, so its local state is preserved.
await expect(u.page.locator('p[data-local-counter="1"]')).toHaveText('Local counter: 2');
});

test.describe('User Button with experimental asStandalone and asProvider', () => {
test('items at the specified order', async ({ page, context }) => {
const u = createTestUtils({ app, page, context });
Expand Down
4 changes: 2 additions & 2 deletions packages/react/src/components/uiComponents.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -127,8 +127,8 @@ type OrganizationSwitcherPropsWithoutCustomPages = Without<
const CustomPortalsRenderer = (props: CustomPortalsRendererProps) => {
return (
<>
{props?.customPagesPortals?.map((portal, index) => createElement(portal, { key: index }))}
{props?.customMenuItemsPortals?.map((portal, index) => createElement(portal, { key: index }))}
{props?.customPagesPortals?.map(({ key, portal }) => createElement(portal, { key }))}
{props?.customMenuItemsPortals?.map(({ key, portal }) => createElement(portal, { key }))}
</>
);
};
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
import { render, screen } from '@testing-library/react';
import React, { createElement, useEffect, useRef } from 'react';
import { afterEach, describe, expect, it, vi } from 'vitest';

import { OrganizationProfilePage } from '../../components/uiComponents';
import { useOrganizationProfileCustomPages } from '../useCustomPages';

vi.mock('@clerk/shared/utils', () => ({
logErrorInDevMode: vi.fn(),
}));

// Per-page mount/unmount counters. A remount re-runs the mount effect.
const mounts: Record<string, number> = {};
const unmounts: Record<string, number> = {};

// Stable component type, defined once. If it remounts across a rerender it is
// because the portal wrapping it changed identity or render key.
const TrackedContent = ({ id, text }: { id: string; text: string }) => {
useEffect(() => {
mounts[id] = (mounts[id] ?? 0) + 1;
return () => {
unmounts[id] = (unmounts[id] ?? 0) + 1;
};
// eslint-disable-next-line react-hooks/exhaustive-deps -- mount-once instrument; id is stable per instance
}, []);
return <div data-testid={`content-${id}`}>{text}</div>;
};

/**
* Faithfully reproduces the production render path for custom pages:
* - useOrganizationProfileCustomPages parses children into { customPages, customPagesPortals }
* - clerk-js calls customPages[i].mount(node) once per logical page (by identity; here keyed by url)
* - CustomPortalsRenderer renders each portal via createElement(portal, { key }) using the STABLE key
*/
const Harness = ({ children, tick }: { children: React.ReactNode; tick: number }) => {
const { customPages, customPagesPortals } = useOrganizationProfileCustomPages(children);
const hostRef = useRef<HTMLDivElement | null>(null);
const mountedUrls = useRef<Set<string>>(new Set());

useEffect(() => {
customPages.forEach(page => {
if (page.mount && page.url && !mountedUrls.current.has(page.url)) {
mountedUrls.current.add(page.url);
const node = document.createElement('div');
hostRef.current?.appendChild(node);
page.mount(node);
}
});
});

return (
<>
<div
data-tick={tick}
ref={hostRef}
/>
{customPagesPortals.map(({ key, portal }) => createElement(portal, { key }))}
</>
);
};

const makePage = (id: string, label: string, url: string, text: string) => (
<OrganizationProfilePage
key={id}
label={label}
labelIcon={<span>i</span>}
url={url}
>
<TrackedContent
id={id}
text={text}
/>
</OrganizationProfilePage>
);

afterEach(() => {
for (const k of Object.keys(mounts)) {
delete mounts[k];
}
for (const k of Object.keys(unmounts)) {
delete unmounts[k];
}
});

describe('custom pages remount behavior (integration through CustomPortalsRenderer path)', () => {
it('does not remount custom page content when the parent rerenders', async () => {
const { rerender } = render(<Harness tick={0}>{[makePage('p1', 'Page 1', 'page-1', 'first')]}</Harness>);

await screen.findByText('first');
expect(mounts['p1']).toBe(1);

// Parent rerenders for an unrelated reason; the page content prop changes but the
// logical page (key/label/url) is identical.
rerender(<Harness tick={1}>{[makePage('p1', 'Page 1', 'page-1', 'second')]}</Harness>);

await screen.findByText('second');
expect(mounts['p1']).toBe(1);
expect(unmounts['p1'] ?? 0).toBe(0);
});

it('does not remount a surviving custom page when another page is inserted before it', async () => {
const second = makePage('second', 'Second', 'second', 'second-content');
const first = makePage('first', 'First', 'first', 'first-content');

const { rerender } = render(<Harness tick={0}>{[second]}</Harness>);
await screen.findByText('second-content');
expect(mounts['second']).toBe(1);

// Insert a new page BEFORE the existing one.
rerender(<Harness tick={1}>{[first, second]}</Harness>);
await screen.findByText('first-content');

// The surviving page keeps its stable key + portal identity, so React reconciles it as an
// update rather than a remount.
expect(mounts['second']).toBe(1);
expect(unmounts['second'] ?? 0).toBe(0);
// The newly inserted page mounts exactly once.
expect(mounts['first']).toBe(1);
});
});
11 changes: 7 additions & 4 deletions packages/react/src/utils/__tests__/useCustomMenuItems.test.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -156,7 +156,8 @@ describe('useUserButtonCustomMenuItems', () => {

expect(result.current.customMenuItems).toHaveLength(2);
expect(result.current.customMenuItemsPortals).toHaveLength(2);
expect(result.current.customMenuItemsPortals[0]).not.toBe(result.current.customMenuItemsPortals[1]);
expect(result.current.customMenuItemsPortals[0].portal).not.toBe(result.current.customMenuItemsPortals[1].portal);
expect(result.current.customMenuItemsPortals[0].key).not.toBe(result.current.customMenuItemsPortals[1].key);
});

it('keeps portal identity with the logical menu item when inserting before it', () => {
Expand DownExpand Up@@ -187,12 +188,14 @@ describe('useUserButtonCustomMenuItems', () => {
},
);

const secondItemIconPortal = result.current.customMenuItemsPortals[0];
const secondItemIconPortal = result.current.customMenuItemsPortals[0].portal;
const secondItemIconKey = result.current.customMenuItemsPortals[0].key;

rerender({ includeFirstItem: true });

expect(result.current.customMenuItems).toHaveLength(2);
expect(result.current.customMenuItemsPortals[0]).not.toBe(secondItemIconPortal);
expect(result.current.customMenuItemsPortals[1]).toBe(secondItemIconPortal);
expect(result.current.customMenuItemsPortals[0].portal).not.toBe(secondItemIconPortal);
expect(result.current.customMenuItemsPortals[1].portal).toBe(secondItemIconPortal);
expect(result.current.customMenuItemsPortals[1].key).toBe(secondItemIconKey);
});
});
26 changes: 18 additions & 8 deletions packages/react/src/utils/__tests__/useCustomPages.test.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -36,8 +36,12 @@ describe('useOrganizationProfileCustomPages', () => {

expect(result.current.customPages).toHaveLength(2);
expect(result.current.customPagesPortals).toHaveLength(4);
expect(result.current.customPagesPortals[0]).not.toBe(result.current.customPagesPortals[2]);
expect(result.current.customPagesPortals[1]).not.toBe(result.current.customPagesPortals[3]);
// Duplicate (same label+url, no key) pages get distinct portal identities...
expect(result.current.customPagesPortals[0].portal).not.toBe(result.current.customPagesPortals[2].portal);
expect(result.current.customPagesPortals[1].portal).not.toBe(result.current.customPagesPortals[3].portal);
// ...and distinct stable render keys.
const keys = result.current.customPagesPortals.map(p => p.key);
expect(new Set(keys).size).toBe(keys.length);
});

it('keeps portal identity with the logical custom page when inserting before it', () => {
Expand DownExpand Up@@ -70,15 +74,21 @@ describe('useOrganizationProfileCustomPages', () => {
},
);

const secondPageContentPortal = result.current.customPagesPortals[0];
const secondPageIconPortal = result.current.customPagesPortals[1];
const secondPageContentPortal = result.current.customPagesPortals[0].portal;
const secondPageContentKey = result.current.customPagesPortals[0].key;
const secondPageIconPortal = result.current.customPagesPortals[1].portal;
const secondPageIconKey = result.current.customPagesPortals[1].key;

rerender({ includeFirstPage: true });

expect(result.current.customPages).toHaveLength(2);
expect(result.current.customPagesPortals[0]).not.toBe(secondPageContentPortal);
expect(result.current.customPagesPortals[1]).not.toBe(secondPageIconPortal);
expect(result.current.customPagesPortals[2]).toBe(secondPageContentPortal);
expect(result.current.customPagesPortals[3]).toBe(secondPageIconPortal);
expect(result.current.customPagesPortals[0].portal).not.toBe(secondPageContentPortal);
expect(result.current.customPagesPortals[1].portal).not.toBe(secondPageIconPortal);
// The second page keeps BOTH its portal identity and its stable render key when it moves
// position, so CustomPortalsRenderer reconciles it as an update instead of a remount.
expect(result.current.customPagesPortals[2].portal).toBe(secondPageContentPortal);
expect(result.current.customPagesPortals[2].key).toBe(secondPageContentKey);
expect(result.current.customPagesPortals[3].portal).toBe(secondPageIconPortal);
expect(result.current.customPagesPortals[3].key).toBe(secondPageIconKey);
});
});
6 changes: 3 additions & 3 deletions packages/react/src/utils/useCustomMenuItems.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -57,7 +57,7 @@ const useCustomMenuItems = ({
}: UseCustomMenuItemsParams) => {
const validChildren: CustomMenuItemType[] = [];
const customMenuItems: CustomMenuItem[] = [];
const customMenuItemsPortals: React.ComponentType[] = [];
const customMenuItemsPortals: Array<{ key: string; portal: React.ComponentType }> = [];
const portalIdCounts = new Map<string, number>();

React.Children.forEach(children, child => {
Expand DownExpand Up@@ -181,7 +181,7 @@ const useCustomMenuItems = ({
menuItem.open = mi.open;
}
customMenuItems.push(menuItem);
customMenuItemsPortals.push(iconPortal);
customMenuItemsPortals.push({ key: `icon:${mi.portalId || index}`, portal: iconPortal });
}
if (isExternalLink(mi)) {
const {
Expand All@@ -195,7 +195,7 @@ const useCustomMenuItems = ({
mountIcon,
unmountIcon,
});
customMenuItemsPortals.push(iconPortal);
customMenuItemsPortals.push({ key: `icon:${mi.portalId || index}`, portal: iconPortal });
}
});

Expand Down
8 changes: 4 additions & 4 deletions packages/react/src/utils/useCustomPages.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -179,7 +179,7 @@ const useCustomPages = (params: UseCustomPagesParams, options?: UseCustomPagesOp
const customLinkLabelIconsPortals = useCustomElementPortal(customLinkLabelIcons);

const customPages: CustomPage[] = [];
const customPagesPortals: React.ComponentType[] = [];
const customPagesPortals: Array<{ key: string; portal: React.ComponentType }> = [];

validChildren.forEach((cp, index) => {
if (isReorderItem(cp, reorderItemsLabels)) {
Expand All@@ -198,8 +198,8 @@ const useCustomPages = (params: UseCustomPagesParams, options?: UseCustomPagesOp
unmount: unmountIcon,
} = customPageLabelIconsPortals.find(p => p.id === (cp.portalId || index)) as UseCustomElementPortalReturn;
customPages.push({ label: cp.label, url: cp.url, mount, unmount, mountIcon, unmountIcon });
customPagesPortals.push(contentPortal);
customPagesPortals.push(labelPortal);
customPagesPortals.push({ key: `content:${cp.portalId || index}`, portal: contentPortal });
customPagesPortals.push({ key: `label:${cp.portalId || index}`, portal: labelPortal });
return;
}
if (isExternalLink(cp)) {
Expand All@@ -209,7 +209,7 @@ const useCustomPages = (params: UseCustomPagesParams, options?: UseCustomPagesOp
unmount: unmountIcon,
} = customLinkLabelIconsPortals.find(p => p.id === (cp.portalId || index)) as UseCustomElementPortalReturn;
customPages.push({ label: cp.label, url: cp.url, mountIcon, unmountIcon });
customPagesPortals.push(labelPortal);
customPagesPortals.push({ key: `label:${cp.portalId || index}`, portal: labelPortal });
return;
}
});
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' fix(react): key custom page portals by stable id by jacekradko · Pull Request #8730 · clerk/javascript · GitHub
Skip to content
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
5 changes: 5 additions & 0 deletions .changeset/custom-page-portal-stable-keys.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
---
'@clerk/react': patch
---

Keep custom pages and menu items mounted when sibling pages are added, removed, or reordered. Portals are now keyed by a stable id rather than their array index, so a surviving page is reconciled as an update instead of being remounted.
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
import { UserProfile } from '@clerk/react';
import { useContext } from 'react';
import { useContext, useState } from 'react';
import { PageContext, PageContextProvider } from '../PageContext.tsx';

function Page1() {
const { counter, setCounter } = useContext(PageContext);
// Local state lives INSIDE the portaled custom page. It only resets if the
// page is remounted, so it is our instrument for detecting remounts.
const [localCounter, setLocalCounter] = useState(0);

return (
<>
Expand All@@ -15,13 +18,31 @@ function Page1() {
>
Update
</button>
<p data-local-counter={1}>Local counter: {localCounter}</p>
<button
data-local-counter={1}
onClick={() => setLocalCounter(a => a + 1)}
>
Increment local
</button>
</>
);
}

export default function Page() {
// Bumping parent state recreates the <UserProfile> element, forcing the
// profile component (and useCustomPages) to rerender. The custom page content
// must survive this without remounting.
const [parentTick, setParentTick] = useState(0);

return (
<PageContextProvider>
<button
data-testid='rerender-parent'
onClick={() => setParentTick(t => t + 1)}
>
Rerender parent: {parentTick}
</button>
<UserProfile
fallback={<>Loading user profile</>}
path={'/custom-user-profile'}
Expand Down
31 changes: 31 additions & 0 deletions integration/tests/custom-pages.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -171,6 +171,37 @@ testAgainstRunningApps({ withPattern: ['react.vite.withEmailCodes'] })(
});
});

test('custom profile page survives a parent rerender without remounting', async ({ page, context }) => {
const u = createTestUtils({ app, page, context });
await u.po.signIn.goTo();
await u.po.signIn.waitForMounted();
await u.po.signIn.signInWithEmailAndInstantPassword({ email: fakeUser.email, password: fakeUser.password });
await u.po.expect.toBeSignedIn();

await u.page.goToRelative(CUSTOM_PROFILE_PAGE);
await u.po.userProfile.waitForMounted();

// Open the custom page (Page 1)
const [profilePage] = await u.page.locator('button.cl-navbarButton__custom-page-0').all();
await profilePage.click();

// Local state lives inside the portaled custom page and starts at 0.
await u.page.waitForSelector('p[data-local-counter="1"]', { state: 'attached' });
await expect(u.page.locator('p[data-local-counter="1"]')).toHaveText('Local counter: 0');

// Mutate the local state to 2.
await u.page.locator('button[data-local-counter="1"]').click();
await u.page.locator('button[data-local-counter="1"]').click();
await expect(u.page.locator('p[data-local-counter="1"]')).toHaveText('Local counter: 2');

// Force a parent rerender: this re-creates the <UserProfile> element and reruns useCustomPages.
await u.page.locator('button[data-testid="rerender-parent"]').click();
await expect(u.page.locator('button[data-testid="rerender-parent"]')).toHaveText('Rerender parent: 1');

// The custom page must NOT remount, so its local state is preserved.
await expect(u.page.locator('p[data-local-counter="1"]')).toHaveText('Local counter: 2');
});

test.describe('User Button with experimental asStandalone and asProvider', () => {
test('items at the specified order', async ({ page, context }) => {
const u = createTestUtils({ app, page, context });
Expand Down
4 changes: 2 additions & 2 deletions packages/react/src/components/uiComponents.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -127,8 +127,8 @@ type OrganizationSwitcherPropsWithoutCustomPages = Without<
const CustomPortalsRenderer = (props: CustomPortalsRendererProps) => {
return (
<>
{props?.customPagesPortals?.map((portal, index) => createElement(portal, { key: index }))}
{props?.customMenuItemsPortals?.map((portal, index) => createElement(portal, { key: index }))}
{props?.customPagesPortals?.map(({ key, portal }) => createElement(portal, { key }))}
{props?.customMenuItemsPortals?.map(({ key, portal }) => createElement(portal, { key }))}
</>
);
};
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
import { render, screen } from '@testing-library/react';
import React, { createElement, useEffect, useRef } from 'react';
import { afterEach, describe, expect, it, vi } from 'vitest';

import { OrganizationProfilePage } from '../../components/uiComponents';
import { useOrganizationProfileCustomPages } from '../useCustomPages';

vi.mock('@clerk/shared/utils', () => ({
logErrorInDevMode: vi.fn(),
}));

// Per-page mount/unmount counters. A remount re-runs the mount effect.
const mounts: Record<string, number> = {};
const unmounts: Record<string, number> = {};

// Stable component type, defined once. If it remounts across a rerender it is
// because the portal wrapping it changed identity or render key.
const TrackedContent = ({ id, text }: { id: string; text: string }) => {
useEffect(() => {
mounts[id] = (mounts[id] ?? 0) + 1;
return () => {
unmounts[id] = (unmounts[id] ?? 0) + 1;
};
// eslint-disable-next-line react-hooks/exhaustive-deps -- mount-once instrument; id is stable per instance
}, []);
return <div data-testid={`content-${id}`}>{text}</div>;
};

/**
* Faithfully reproduces the production render path for custom pages:
* - useOrganizationProfileCustomPages parses children into { customPages, customPagesPortals }
* - clerk-js calls customPages[i].mount(node) once per logical page (by identity; here keyed by url)
* - CustomPortalsRenderer renders each portal via createElement(portal, { key }) using the STABLE key
*/
const Harness = ({ children, tick }: { children: React.ReactNode; tick: number }) => {
const { customPages, customPagesPortals } = useOrganizationProfileCustomPages(children);
const hostRef = useRef<HTMLDivElement | null>(null);
const mountedUrls = useRef<Set<string>>(new Set());

useEffect(() => {
customPages.forEach(page => {
if (page.mount && page.url && !mountedUrls.current.has(page.url)) {
mountedUrls.current.add(page.url);
const node = document.createElement('div');
hostRef.current?.appendChild(node);
page.mount(node);
}
});
});

return (
<>
<div
data-tick={tick}
ref={hostRef}
/>
{customPagesPortals.map(({ key, portal }) => createElement(portal, { key }))}
</>
);
};

const makePage = (id: string, label: string, url: string, text: string) => (
<OrganizationProfilePage
key={id}
label={label}
labelIcon={<span>i</span>}
url={url}
>
<TrackedContent
id={id}
text={text}
/>
</OrganizationProfilePage>
);

afterEach(() => {
for (const k of Object.keys(mounts)) {
delete mounts[k];
}
for (const k of Object.keys(unmounts)) {
delete unmounts[k];
}
});

describe('custom pages remount behavior (integration through CustomPortalsRenderer path)', () => {
it('does not remount custom page content when the parent rerenders', async () => {
const { rerender } = render(<Harness tick={0}>{[makePage('p1', 'Page 1', 'page-1', 'first')]}</Harness>);

await screen.findByText('first');
expect(mounts['p1']).toBe(1);

// Parent rerenders for an unrelated reason; the page content prop changes but the
// logical page (key/label/url) is identical.
rerender(<Harness tick={1}>{[makePage('p1', 'Page 1', 'page-1', 'second')]}</Harness>);

await screen.findByText('second');
expect(mounts['p1']).toBe(1);
expect(unmounts['p1'] ?? 0).toBe(0);
});

it('does not remount a surviving custom page when another page is inserted before it', async () => {
const second = makePage('second', 'Second', 'second', 'second-content');
const first = makePage('first', 'First', 'first', 'first-content');

const { rerender } = render(<Harness tick={0}>{[second]}</Harness>);
await screen.findByText('second-content');
expect(mounts['second']).toBe(1);

// Insert a new page BEFORE the existing one.
rerender(<Harness tick={1}>{[first, second]}</Harness>);
await screen.findByText('first-content');

// The surviving page keeps its stable key + portal identity, so React reconciles it as an
// update rather than a remount.
expect(mounts['second']).toBe(1);
expect(unmounts['second'] ?? 0).toBe(0);
// The newly inserted page mounts exactly once.
expect(mounts['first']).toBe(1);
});
});
11 changes: 7 additions & 4 deletions packages/react/src/utils/__tests__/useCustomMenuItems.test.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -156,7 +156,8 @@ describe('useUserButtonCustomMenuItems', () => {

expect(result.current.customMenuItems).toHaveLength(2);
expect(result.current.customMenuItemsPortals).toHaveLength(2);
expect(result.current.customMenuItemsPortals[0]).not.toBe(result.current.customMenuItemsPortals[1]);
expect(result.current.customMenuItemsPortals[0].portal).not.toBe(result.current.customMenuItemsPortals[1].portal);
expect(result.current.customMenuItemsPortals[0].key).not.toBe(result.current.customMenuItemsPortals[1].key);
});

it('keeps portal identity with the logical menu item when inserting before it', () => {
Expand DownExpand Up@@ -187,12 +188,14 @@ describe('useUserButtonCustomMenuItems', () => {
},
);

const secondItemIconPortal = result.current.customMenuItemsPortals[0];
const secondItemIconPortal = result.current.customMenuItemsPortals[0].portal;
const secondItemIconKey = result.current.customMenuItemsPortals[0].key;

rerender({ includeFirstItem: true });

expect(result.current.customMenuItems).toHaveLength(2);
expect(result.current.customMenuItemsPortals[0]).not.toBe(secondItemIconPortal);
expect(result.current.customMenuItemsPortals[1]).toBe(secondItemIconPortal);
expect(result.current.customMenuItemsPortals[0].portal).not.toBe(secondItemIconPortal);
expect(result.current.customMenuItemsPortals[1].portal).toBe(secondItemIconPortal);
expect(result.current.customMenuItemsPortals[1].key).toBe(secondItemIconKey);
});
});
26 changes: 18 additions & 8 deletions packages/react/src/utils/__tests__/useCustomPages.test.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -36,8 +36,12 @@ describe('useOrganizationProfileCustomPages', () => {

expect(result.current.customPages).toHaveLength(2);
expect(result.current.customPagesPortals).toHaveLength(4);
expect(result.current.customPagesPortals[0]).not.toBe(result.current.customPagesPortals[2]);
expect(result.current.customPagesPortals[1]).not.toBe(result.current.customPagesPortals[3]);
// Duplicate (same label+url, no key) pages get distinct portal identities...
expect(result.current.customPagesPortals[0].portal).not.toBe(result.current.customPagesPortals[2].portal);
expect(result.current.customPagesPortals[1].portal).not.toBe(result.current.customPagesPortals[3].portal);
// ...and distinct stable render keys.
const keys = result.current.customPagesPortals.map(p => p.key);
expect(new Set(keys).size).toBe(keys.length);
});

it('keeps portal identity with the logical custom page when inserting before it', () => {
Expand DownExpand Up@@ -70,15 +74,21 @@ describe('useOrganizationProfileCustomPages', () => {
},
);

const secondPageContentPortal = result.current.customPagesPortals[0];
const secondPageIconPortal = result.current.customPagesPortals[1];
const secondPageContentPortal = result.current.customPagesPortals[0].portal;
const secondPageContentKey = result.current.customPagesPortals[0].key;
const secondPageIconPortal = result.current.customPagesPortals[1].portal;
const secondPageIconKey = result.current.customPagesPortals[1].key;

rerender({ includeFirstPage: true });

expect(result.current.customPages).toHaveLength(2);
expect(result.current.customPagesPortals[0]).not.toBe(secondPageContentPortal);
expect(result.current.customPagesPortals[1]).not.toBe(secondPageIconPortal);
expect(result.current.customPagesPortals[2]).toBe(secondPageContentPortal);
expect(result.current.customPagesPortals[3]).toBe(secondPageIconPortal);
expect(result.current.customPagesPortals[0].portal).not.toBe(secondPageContentPortal);
expect(result.current.customPagesPortals[1].portal).not.toBe(secondPageIconPortal);
// The second page keeps BOTH its portal identity and its stable render key when it moves
// position, so CustomPortalsRenderer reconciles it as an update instead of a remount.
expect(result.current.customPagesPortals[2].portal).toBe(secondPageContentPortal);
expect(result.current.customPagesPortals[2].key).toBe(secondPageContentKey);
expect(result.current.customPagesPortals[3].portal).toBe(secondPageIconPortal);
expect(result.current.customPagesPortals[3].key).toBe(secondPageIconKey);
});
});
6 changes: 3 additions & 3 deletions packages/react/src/utils/useCustomMenuItems.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -57,7 +57,7 @@ const useCustomMenuItems = ({
}: UseCustomMenuItemsParams) => {
const validChildren: CustomMenuItemType[] = [];
const customMenuItems: CustomMenuItem[] = [];
const customMenuItemsPortals: React.ComponentType[] = [];
const customMenuItemsPortals: Array<{ key: string; portal: React.ComponentType }> = [];
const portalIdCounts = new Map<string, number>();

React.Children.forEach(children, child => {
Expand DownExpand Up@@ -181,7 +181,7 @@ const useCustomMenuItems = ({
menuItem.open = mi.open;
}
customMenuItems.push(menuItem);
customMenuItemsPortals.push(iconPortal);
customMenuItemsPortals.push({ key: `icon:${mi.portalId || index}`, portal: iconPortal });
}
if (isExternalLink(mi)) {
const {
Expand All@@ -195,7 +195,7 @@ const useCustomMenuItems = ({
mountIcon,
unmountIcon,
});
customMenuItemsPortals.push(iconPortal);
customMenuItemsPortals.push({ key: `icon:${mi.portalId || index}`, portal: iconPortal });
}
});

Expand Down
8 changes: 4 additions & 4 deletions packages/react/src/utils/useCustomPages.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -179,7 +179,7 @@ const useCustomPages = (params: UseCustomPagesParams, options?: UseCustomPagesOp
const customLinkLabelIconsPortals = useCustomElementPortal(customLinkLabelIcons);

const customPages: CustomPage[] = [];
const customPagesPortals: React.ComponentType[] = [];
const customPagesPortals: Array<{ key: string; portal: React.ComponentType }> = [];

validChildren.forEach((cp, index) => {
if (isReorderItem(cp, reorderItemsLabels)) {
Expand All@@ -198,8 +198,8 @@ const useCustomPages = (params: UseCustomPagesParams, options?: UseCustomPagesOp
unmount: unmountIcon,
} = customPageLabelIconsPortals.find(p => p.id === (cp.portalId || index)) as UseCustomElementPortalReturn;
customPages.push({ label: cp.label, url: cp.url, mount, unmount, mountIcon, unmountIcon });
customPagesPortals.push(contentPortal);
customPagesPortals.push(labelPortal);
customPagesPortals.push({ key: `content:${cp.portalId || index}`, portal: contentPortal });
customPagesPortals.push({ key: `label:${cp.portalId || index}`, portal: labelPortal });
return;
}
if (isExternalLink(cp)) {
Expand All@@ -209,7 +209,7 @@ const useCustomPages = (params: UseCustomPagesParams, options?: UseCustomPagesOp
unmount: unmountIcon,
} = customLinkLabelIconsPortals.find(p => p.id === (cp.portalId || index)) as UseCustomElementPortalReturn;
customPages.push({ label: cp.label, url: cp.url, mountIcon, unmountIcon });
customPagesPortals.push(labelPortal);
customPagesPortals.push({ key: `label:${cp.portalId || index}`, portal: labelPortal });
return;
}
});
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); fix(react): key custom page portals by stable id by jacekradko · Pull Request #8730 · clerk/javascript · GitHub
Skip to content
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
5 changes: 5 additions & 0 deletions .changeset/custom-page-portal-stable-keys.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
---
'@clerk/react': patch
---

Keep custom pages and menu items mounted when sibling pages are added, removed, or reordered. Portals are now keyed by a stable id rather than their array index, so a surviving page is reconciled as an update instead of being remounted.
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
import { UserProfile } from '@clerk/react';
import { useContext } from 'react';
import { useContext, useState } from 'react';
import { PageContext, PageContextProvider } from '../PageContext.tsx';

function Page1() {
const { counter, setCounter } = useContext(PageContext);
// Local state lives INSIDE the portaled custom page. It only resets if the
// page is remounted, so it is our instrument for detecting remounts.
const [localCounter, setLocalCounter] = useState(0);

return (
<>
Expand All@@ -15,13 +18,31 @@ function Page1() {
>
Update
</button>
<p data-local-counter={1}>Local counter: {localCounter}</p>
<button
data-local-counter={1}
onClick={() => setLocalCounter(a => a + 1)}
>
Increment local
</button>
</>
);
}

export default function Page() {
// Bumping parent state recreates the <UserProfile> element, forcing the
// profile component (and useCustomPages) to rerender. The custom page content
// must survive this without remounting.
const [parentTick, setParentTick] = useState(0);

return (
<PageContextProvider>
<button
data-testid='rerender-parent'
onClick={() => setParentTick(t => t + 1)}
>
Rerender parent: {parentTick}
</button>
<UserProfile
fallback={<>Loading user profile</>}
path={'/custom-user-profile'}
Expand Down
31 changes: 31 additions & 0 deletions integration/tests/custom-pages.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -171,6 +171,37 @@ testAgainstRunningApps({ withPattern: ['react.vite.withEmailCodes'] })(
});
});

test('custom profile page survives a parent rerender without remounting', async ({ page, context }) => {
const u = createTestUtils({ app, page, context });
await u.po.signIn.goTo();
await u.po.signIn.waitForMounted();
await u.po.signIn.signInWithEmailAndInstantPassword({ email: fakeUser.email, password: fakeUser.password });
await u.po.expect.toBeSignedIn();

await u.page.goToRelative(CUSTOM_PROFILE_PAGE);
await u.po.userProfile.waitForMounted();

// Open the custom page (Page 1)
const [profilePage] = await u.page.locator('button.cl-navbarButton__custom-page-0').all();
await profilePage.click();

// Local state lives inside the portaled custom page and starts at 0.
await u.page.waitForSelector('p[data-local-counter="1"]', { state: 'attached' });
await expect(u.page.locator('p[data-local-counter="1"]')).toHaveText('Local counter: 0');

// Mutate the local state to 2.
await u.page.locator('button[data-local-counter="1"]').click();
await u.page.locator('button[data-local-counter="1"]').click();
await expect(u.page.locator('p[data-local-counter="1"]')).toHaveText('Local counter: 2');

// Force a parent rerender: this re-creates the <UserProfile> element and reruns useCustomPages.
await u.page.locator('button[data-testid="rerender-parent"]').click();
await expect(u.page.locator('button[data-testid="rerender-parent"]')).toHaveText('Rerender parent: 1');

// The custom page must NOT remount, so its local state is preserved.
await expect(u.page.locator('p[data-local-counter="1"]')).toHaveText('Local counter: 2');
});

test.describe('User Button with experimental asStandalone and asProvider', () => {
test('items at the specified order', async ({ page, context }) => {
const u = createTestUtils({ app, page, context });
Expand Down
4 changes: 2 additions & 2 deletions packages/react/src/components/uiComponents.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -127,8 +127,8 @@ type OrganizationSwitcherPropsWithoutCustomPages = Without<
const CustomPortalsRenderer = (props: CustomPortalsRendererProps) => {
return (
<>
{props?.customPagesPortals?.map((portal, index) => createElement(portal, { key: index }))}
{props?.customMenuItemsPortals?.map((portal, index) => createElement(portal, { key: index }))}
{props?.customPagesPortals?.map(({ key, portal }) => createElement(portal, { key }))}
{props?.customMenuItemsPortals?.map(({ key, portal }) => createElement(portal, { key }))}
</>
);
};
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
import { render, screen } from '@testing-library/react';
import React, { createElement, useEffect, useRef } from 'react';
import { afterEach, describe, expect, it, vi } from 'vitest';

import { OrganizationProfilePage } from '../../components/uiComponents';
import { useOrganizationProfileCustomPages } from '../useCustomPages';

vi.mock('@clerk/shared/utils', () => ({
logErrorInDevMode: vi.fn(),
}));

// Per-page mount/unmount counters. A remount re-runs the mount effect.
const mounts: Record<string, number> = {};
const unmounts: Record<string, number> = {};

// Stable component type, defined once. If it remounts across a rerender it is
// because the portal wrapping it changed identity or render key.
const TrackedContent = ({ id, text }: { id: string; text: string }) => {
useEffect(() => {
mounts[id] = (mounts[id] ?? 0) + 1;
return () => {
unmounts[id] = (unmounts[id] ?? 0) + 1;
};
// eslint-disable-next-line react-hooks/exhaustive-deps -- mount-once instrument; id is stable per instance
}, []);
return <div data-testid={`content-${id}`}>{text}</div>;
};

/**
* Faithfully reproduces the production render path for custom pages:
* - useOrganizationProfileCustomPages parses children into { customPages, customPagesPortals }
* - clerk-js calls customPages[i].mount(node) once per logical page (by identity; here keyed by url)
* - CustomPortalsRenderer renders each portal via createElement(portal, { key }) using the STABLE key
*/
const Harness = ({ children, tick }: { children: React.ReactNode; tick: number }) => {
const { customPages, customPagesPortals } = useOrganizationProfileCustomPages(children);
const hostRef = useRef<HTMLDivElement | null>(null);
const mountedUrls = useRef<Set<string>>(new Set());

useEffect(() => {
customPages.forEach(page => {
if (page.mount && page.url && !mountedUrls.current.has(page.url)) {
mountedUrls.current.add(page.url);
const node = document.createElement('div');
hostRef.current?.appendChild(node);
page.mount(node);
}
});
});

return (
<>
<div
data-tick={tick}
ref={hostRef}
/>
{customPagesPortals.map(({ key, portal }) => createElement(portal, { key }))}
</>
);
};

const makePage = (id: string, label: string, url: string, text: string) => (
<OrganizationProfilePage
key={id}
label={label}
labelIcon={<span>i</span>}
url={url}
>
<TrackedContent
id={id}
text={text}
/>
</OrganizationProfilePage>
);

afterEach(() => {
for (const k of Object.keys(mounts)) {
delete mounts[k];
}
for (const k of Object.keys(unmounts)) {
delete unmounts[k];
}
});

describe('custom pages remount behavior (integration through CustomPortalsRenderer path)', () => {
it('does not remount custom page content when the parent rerenders', async () => {
const { rerender } = render(<Harness tick={0}>{[makePage('p1', 'Page 1', 'page-1', 'first')]}</Harness>);

await screen.findByText('first');
expect(mounts['p1']).toBe(1);

// Parent rerenders for an unrelated reason; the page content prop changes but the
// logical page (key/label/url) is identical.
rerender(<Harness tick={1}>{[makePage('p1', 'Page 1', 'page-1', 'second')]}</Harness>);

await screen.findByText('second');
expect(mounts['p1']).toBe(1);
expect(unmounts['p1'] ?? 0).toBe(0);
});

it('does not remount a surviving custom page when another page is inserted before it', async () => {
const second = makePage('second', 'Second', 'second', 'second-content');
const first = makePage('first', 'First', 'first', 'first-content');

const { rerender } = render(<Harness tick={0}>{[second]}</Harness>);
await screen.findByText('second-content');
expect(mounts['second']).toBe(1);

// Insert a new page BEFORE the existing one.
rerender(<Harness tick={1}>{[first, second]}</Harness>);
await screen.findByText('first-content');

// The surviving page keeps its stable key + portal identity, so React reconciles it as an
// update rather than a remount.
expect(mounts['second']).toBe(1);
expect(unmounts['second'] ?? 0).toBe(0);
// The newly inserted page mounts exactly once.
expect(mounts['first']).toBe(1);
});
});
11 changes: 7 additions & 4 deletions packages/react/src/utils/__tests__/useCustomMenuItems.test.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -156,7 +156,8 @@ describe('useUserButtonCustomMenuItems', () => {

expect(result.current.customMenuItems).toHaveLength(2);
expect(result.current.customMenuItemsPortals).toHaveLength(2);
expect(result.current.customMenuItemsPortals[0]).not.toBe(result.current.customMenuItemsPortals[1]);
expect(result.current.customMenuItemsPortals[0].portal).not.toBe(result.current.customMenuItemsPortals[1].portal);
expect(result.current.customMenuItemsPortals[0].key).not.toBe(result.current.customMenuItemsPortals[1].key);
});

it('keeps portal identity with the logical menu item when inserting before it', () => {
Expand DownExpand Up@@ -187,12 +188,14 @@ describe('useUserButtonCustomMenuItems', () => {
},
);

const secondItemIconPortal = result.current.customMenuItemsPortals[0];
const secondItemIconPortal = result.current.customMenuItemsPortals[0].portal;
const secondItemIconKey = result.current.customMenuItemsPortals[0].key;

rerender({ includeFirstItem: true });

expect(result.current.customMenuItems).toHaveLength(2);
expect(result.current.customMenuItemsPortals[0]).not.toBe(secondItemIconPortal);
expect(result.current.customMenuItemsPortals[1]).toBe(secondItemIconPortal);
expect(result.current.customMenuItemsPortals[0].portal).not.toBe(secondItemIconPortal);
expect(result.current.customMenuItemsPortals[1].portal).toBe(secondItemIconPortal);
expect(result.current.customMenuItemsPortals[1].key).toBe(secondItemIconKey);
});
});
26 changes: 18 additions & 8 deletions packages/react/src/utils/__tests__/useCustomPages.test.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -36,8 +36,12 @@ describe('useOrganizationProfileCustomPages', () => {

expect(result.current.customPages).toHaveLength(2);
expect(result.current.customPagesPortals).toHaveLength(4);
expect(result.current.customPagesPortals[0]).not.toBe(result.current.customPagesPortals[2]);
expect(result.current.customPagesPortals[1]).not.toBe(result.current.customPagesPortals[3]);
// Duplicate (same label+url, no key) pages get distinct portal identities...
expect(result.current.customPagesPortals[0].portal).not.toBe(result.current.customPagesPortals[2].portal);
expect(result.current.customPagesPortals[1].portal).not.toBe(result.current.customPagesPortals[3].portal);
// ...and distinct stable render keys.
const keys = result.current.customPagesPortals.map(p => p.key);
expect(new Set(keys).size).toBe(keys.length);
});

it('keeps portal identity with the logical custom page when inserting before it', () => {
Expand DownExpand Up@@ -70,15 +74,21 @@ describe('useOrganizationProfileCustomPages', () => {
},
);

const secondPageContentPortal = result.current.customPagesPortals[0];
const secondPageIconPortal = result.current.customPagesPortals[1];
const secondPageContentPortal = result.current.customPagesPortals[0].portal;
const secondPageContentKey = result.current.customPagesPortals[0].key;
const secondPageIconPortal = result.current.customPagesPortals[1].portal;
const secondPageIconKey = result.current.customPagesPortals[1].key;

rerender({ includeFirstPage: true });

expect(result.current.customPages).toHaveLength(2);
expect(result.current.customPagesPortals[0]).not.toBe(secondPageContentPortal);
expect(result.current.customPagesPortals[1]).not.toBe(secondPageIconPortal);
expect(result.current.customPagesPortals[2]).toBe(secondPageContentPortal);
expect(result.current.customPagesPortals[3]).toBe(secondPageIconPortal);
expect(result.current.customPagesPortals[0].portal).not.toBe(secondPageContentPortal);
expect(result.current.customPagesPortals[1].portal).not.toBe(secondPageIconPortal);
// The second page keeps BOTH its portal identity and its stable render key when it moves
// position, so CustomPortalsRenderer reconciles it as an update instead of a remount.
expect(result.current.customPagesPortals[2].portal).toBe(secondPageContentPortal);
expect(result.current.customPagesPortals[2].key).toBe(secondPageContentKey);
expect(result.current.customPagesPortals[3].portal).toBe(secondPageIconPortal);
expect(result.current.customPagesPortals[3].key).toBe(secondPageIconKey);
});
});
6 changes: 3 additions & 3 deletions packages/react/src/utils/useCustomMenuItems.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -57,7 +57,7 @@ const useCustomMenuItems = ({
}: UseCustomMenuItemsParams) => {
const validChildren: CustomMenuItemType[] = [];
const customMenuItems: CustomMenuItem[] = [];
const customMenuItemsPortals: React.ComponentType[] = [];
const customMenuItemsPortals: Array<{ key: string; portal: React.ComponentType }> = [];
const portalIdCounts = new Map<string, number>();

React.Children.forEach(children, child => {
Expand DownExpand Up@@ -181,7 +181,7 @@ const useCustomMenuItems = ({
menuItem.open = mi.open;
}
customMenuItems.push(menuItem);
customMenuItemsPortals.push(iconPortal);
customMenuItemsPortals.push({ key: `icon:${mi.portalId || index}`, portal: iconPortal });
}
if (isExternalLink(mi)) {
const {
Expand All@@ -195,7 +195,7 @@ const useCustomMenuItems = ({
mountIcon,
unmountIcon,
});
customMenuItemsPortals.push(iconPortal);
customMenuItemsPortals.push({ key: `icon:${mi.portalId || index}`, portal: iconPortal });
}
});

Expand Down
8 changes: 4 additions & 4 deletions packages/react/src/utils/useCustomPages.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -179,7 +179,7 @@ const useCustomPages = (params: UseCustomPagesParams, options?: UseCustomPagesOp
const customLinkLabelIconsPortals = useCustomElementPortal(customLinkLabelIcons);

const customPages: CustomPage[] = [];
const customPagesPortals: React.ComponentType[] = [];
const customPagesPortals: Array<{ key: string; portal: React.ComponentType }> = [];

validChildren.forEach((cp, index) => {
if (isReorderItem(cp, reorderItemsLabels)) {
Expand All@@ -198,8 +198,8 @@ const useCustomPages = (params: UseCustomPagesParams, options?: UseCustomPagesOp
unmount: unmountIcon,
} = customPageLabelIconsPortals.find(p => p.id === (cp.portalId || index)) as UseCustomElementPortalReturn;
customPages.push({ label: cp.label, url: cp.url, mount, unmount, mountIcon, unmountIcon });
customPagesPortals.push(contentPortal);
customPagesPortals.push(labelPortal);
customPagesPortals.push({ key: `content:${cp.portalId || index}`, portal: contentPortal });
customPagesPortals.push({ key: `label:${cp.portalId || index}`, portal: labelPortal });
return;
}
if (isExternalLink(cp)) {
Expand All@@ -209,7 +209,7 @@ const useCustomPages = (params: UseCustomPagesParams, options?: UseCustomPagesOp
unmount: unmountIcon,
} = customLinkLabelIconsPortals.find(p => p.id === (cp.portalId || index)) as UseCustomElementPortalReturn;
customPages.push({ label: cp.label, url: cp.url, mountIcon, unmountIcon });
customPagesPortals.push(labelPortal);
customPagesPortals.push({ key: `label:${cp.portalId || index}`, portal: labelPortal });
return;
}
});
Expand Down
Loading