-
Notifications
You must be signed in to change notification settings - Fork 382
fix(clerk-js,clerk-react): Avoid CLS when fallback
is passed to PricingTable
#6644
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
fix(clerk-js,clerk-react): Avoid CLS when fallback
is passed to PricingTable
#6644
Conversation
🦋 Changeset detectedLatest commit: 943da66 The changes in this PR will be included in the next version bump. This PR includes changesets to release 9 packages
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
The latest updates on your projects. Learn more about Vercel for GitHub.
|
WalkthroughAdds a readiness signal for PricingTable rendering: Flow.Root and InvisibleRootBox accept/propagate an isFlowReady flag and set a Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant App as App UI
participant PT as PricingTable
participant FlowRoot as Flow.Root
participant IRB as InvisibleRootBox
participant Hook as useWaitForComponentMount
participant DOM as DOM
App->>PT: render PricingTable
PT->>PT: compute isFlowReady = clerk.isSignedIn ? !!subscription : plans.length > 0
PT->>FlowRoot: render with isFlowReady
FlowRoot->>IRB: render InvisibleRootBox (receives isFlowReady)
IRB->>DOM: setAttribute('class', ...)
IRB->>DOM: setAttribute('data-component-status', 'ready' or 'awaiting-data')
App->>Hook: waitForComponentMount(selector='[data-component-status="ready"]')
Hook->>DOM: observe mutations / initial check
alt selector matches
Hook-->>App: 'rendered'
else timeout/error
Hook-->>App: 'error'
end
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Poem
✨ Finishing Touches
🧪 Generate unit tests
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
Status, Documentation and Community
|
@clerk/agent-toolkit
@clerk/astro
@clerk/backend
@clerk/chrome-extension
@clerk/clerk-js
@clerk/dev-cli
@clerk/elements
@clerk/clerk-expo
@clerk/expo-passkeys
@clerk/express
@clerk/fastify
@clerk/localizations
@clerk/nextjs
@clerk/nuxt
@clerk/clerk-react
@clerk/react-router
@clerk/remix
@clerk/shared
@clerk/tanstack-react-start
@clerk/testing
@clerk/themes
@clerk/types
@clerk/upgrade
@clerk/vue
commit: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/react/src/utils/useWaitForComponentMount.ts (1)
74-92
: Prevent setState on unmounted and reset watcher when component changesIf the component using this hook unmounts before the promise resolves, setStatus may still run. Also, when the component param changes, watcherRef should reset to create a new watcher.
useEffect(() => { + let isMounted = true; + watcherRef.current = undefined; if (!component) { throw new Error('Clerk: no component name provided, unable to detect mount.'); } if (typeof window !== 'undefined' && !watcherRef.current) { const selector = `[data-clerk-component="${component}"]`; const needsReadyAttribute = component === 'PricingTable'; watcherRef.current = waitForElementChildren({ selector, check: needsReadyAttribute ? el => el?.getAttribute('data-ready') === 'true' : undefined, }) - .then(() => { - setStatus('rendered'); - }) - .catch(() => { - setStatus('error'); - }); + .then(() => { + if (isMounted) setStatus('rendered'); + }) + .catch(() => { + if (isMounted) setStatus('error'); + }); } - }, [component]); + return () => { + isMounted = false; + watcherRef.current = undefined; + }; + }, [component]);
🧹 Nitpick comments (5)
.changeset/floppy-glasses-share.md (1)
1-6
: Changeset looks correct and scoped to patch releasesPackages and note align with the implementation goal to avoid CLS by waiting for data readiness. Consider making the note slightly more explicit for consumers: “PricingTable now hides fallback only after data-ready is signaled to prevent CLS.”
Apply this minimal tweak:
-Wait for pricing table data to be ready before hiding its fallback. +PricingTable: wait for data readiness (data-ready="true") before hiding fallback to prevent CLS.packages/clerk-js/src/ui/elements/contexts/index.tsx (2)
137-141
: Memo deps and payload scope
- setRootElement is stable; including it in deps is unnecessary. Use flow, part, rootElement.
- Avoid spreading props directly to the context value, as it also carries children. Spread only the fields you intend to expose (flow, part) to prevent accidental context bloat.
Apply:
- const value = React.useMemo( - () => ({ value: { ...props, rootElement, setRootElement } }), - [flow, part, rootElement, setRootElement], - ); + const value = React.useMemo( + () => ({ value: { flow, part, rootElement, setRootElement } }), + [flow, part, rootElement], + );
100-104
: Duplicate union member 'subscriptionDetails'Union type lists 'subscriptionDetails' twice. Remove the duplicate to keep the type clean.
- | 'subscriptionDetails' - | 'subscriptionDetails' + | 'subscriptionDetails'packages/react/src/utils/useWaitForComponentMount.ts (1)
41-47
: Reduce observer cost: retarget to the actual element and filter observed attributesCurrently observing the entire root subtree for all attributes can be noisy. Once the target element is found, switch the observer to that element and use attributeFilter when check is provided (e.g., data-ready).
- const observer = new MutationObserver(mutationsList => { + const observer = new MutationObserver(mutationsList => { for (const mutation of mutationsList) { - if (!elementToWatch && selector) { - elementToWatch = root?.querySelector(selector); - } + if (!elementToWatch && selector) { + const el = root?.querySelector(selector); + if (el) { + elementToWatch = el as HTMLElement; + // Re-target to the specific element to cut noise. + observer.disconnect(); + observer.observe(elementToWatch, { + childList: true, + attributes: true, + subtree: false, + attributeFilter: typeof check === 'function' ? ['data-ready'] : undefined, + }); + } + } - if (mutation.type === 'childList' || mutation.type === 'attributes') { + if (mutation.type === 'childList' || mutation.type === 'attributes') { if (isReady(elementToWatch)) { observer.disconnect(); resolve(); return; } } } }); - observer.observe(root, { childList: true, attributes: true, subtree: true }); + observer.observe(root, { childList: true, attributes: true, subtree: true });Also applies to: 55-55
packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx (1)
18-27
: Optional: remove readiness flag when not readyNot strictly required, but if UI states can toggle, consider removing the attribute when not ready to keep contract clear.
- if (isReady) { - rootElement?.setAttribute('data-ready', 'true'); - } + if (!rootElement) return; + if (isReady) { + rootElement.setAttribute('data-ready', 'true'); + } else { + rootElement.removeAttribute('data-ready'); + }
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (5)
.changeset/floppy-glasses-share.md
(1 hunks)packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
(2 hunks)packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx
(2 hunks)packages/clerk-js/src/ui/elements/contexts/index.tsx
(1 hunks)packages/react/src/utils/useWaitForComponentMount.ts
(4 hunks)
🧰 Additional context used
📓 Path-based instructions (10)
.changeset/**
📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Automated releases must use Changesets.
Files:
.changeset/floppy-glasses-share.md
packages/clerk-js/src/ui/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/clerk-js-ui.mdc)
packages/clerk-js/src/ui/**/*.{ts,tsx}
: Element descriptors should always be camelCase
Use element descriptors in UI components to enable consistent theming and styling via appearance.elements
Element descriptors should generate unique, stable CSS classes for theming
Element descriptors should handle state classes (e.g., cl-loading, cl-active, cl-error, cl-open) automatically based on component state
Do not render hard-coded values; all user-facing strings must be localized using provided localization methods
Use the useLocalizations hook and localizationKeys utility for all text and error messages
Use the styled system (sx prop, theme tokens, responsive values) for custom component styling
Use useCardState for card-level state, useFormState for form-level state, and useLoadingStatus for loading states
Always use handleError utility for API errors and use translateError for localized error messages
Use useFormControl for form field state, implement proper validation, and handle loading and error states in forms
Use localization keys for all form labels and placeholders
Use element descriptors for consistent styling and follow the theme token system
Use the Card and FormContainer patterns for consistent UI structure
Files:
packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx
packages/clerk-js/src/ui/elements/contexts/index.tsx
**/*.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
**/*.{js,jsx,ts,tsx}
: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels
Files:
packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx
packages/react/src/utils/useWaitForComponentMount.ts
packages/clerk-js/src/ui/elements/contexts/index.tsx
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Use Prettier for consistent code formatting
Files:
packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx
packages/react/src/utils/useWaitForComponentMount.ts
packages/clerk-js/src/ui/elements/contexts/index.tsx
packages/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx
packages/react/src/utils/useWaitForComponentMount.ts
packages/clerk-js/src/ui/elements/contexts/index.tsx
packages/**/*.{ts,tsx,d.ts}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Packages should export TypeScript types alongside runtime code
Files:
packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx
packages/react/src/utils/useWaitForComponentMount.ts
packages/clerk-js/src/ui/elements/contexts/index.tsx
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Use proper TypeScript error types
**/*.{ts,tsx}
: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoidany
type - preferunknown
when type is uncertain, then narrow with type guards
Useinterface
for object shapes that might be extended
Usetype
for unions, primitives, and computed types
Preferreadonly
properties for immutable data structures
Useprivate
for internal implementation details
Useprotected
for inheritance hierarchies
Usepublic
explicitly for clarity in public APIs
Preferreadonly
for properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Useconst assertions
for literal types:as const
Usesatisfies
operator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports:import type { ... } from ...
Noany
types without justification
Proper error handling with typed errors
Consistent use ofreadonly
for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)
Files:
packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx
packages/react/src/utils/useWaitForComponentMount.ts
packages/clerk-js/src/ui/elements/contexts/index.tsx
**/*.{jsx,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
**/*.{jsx,tsx}
: Use error boundaries in React components
Minimize re-renders in React components
**/*.{jsx,tsx}
: Always use functional components with hooks instead of class components
Follow PascalCase naming for components:UserProfile
,NavigationMenu
Keep components focused on a single responsibility - split large components
Limit component size to 150-200 lines; extract logic into custom hooks
Use composition over inheritance - prefer smaller, composable components
Export components as named exports for better tree-shaking
One component per file with matching filename and component name
Use useState for simple state management
Use useReducer for complex state logic
Implement proper state initialization
Use proper state updates with callbacks
Implement proper state cleanup
Use Context API for theme/authentication
Implement proper state selectors
Use proper state normalization
Implement proper state persistence
Use React.memo for expensive components
Implement proper useCallback for handlers
Use proper useMemo for expensive computations
Implement proper virtualization for lists
Use proper code splitting with React.lazy
Implement proper cleanup in useEffect
Use proper refs for DOM access
Implement proper event listener cleanup
Use proper abort controllers for fetch
Implement proper subscription cleanup
Use proper HTML elements
Implement proper ARIA attributes
Use proper heading hierarchy
Implement proper form labels
Use proper button types
Implement proper focus management
Use proper keyboard shortcuts
Implement proper tab order
Use proper skip links
Implement proper focus traps
Implement proper error boundaries
Use proper error logging
Implement proper error recovery
Use proper error messages
Implement proper error fallbacks
Use proper form validation
Implement proper error states
Use proper error messages
Implement proper form submission
Use proper form reset
Use proper component naming
Implement proper file naming
Use proper prop naming
Implement proper...
Files:
packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx
packages/clerk-js/src/ui/elements/contexts/index.tsx
**/*.{js,ts,tsx,jsx}
📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.
Files:
packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx
packages/react/src/utils/useWaitForComponentMount.ts
packages/clerk-js/src/ui/elements/contexts/index.tsx
**/*.tsx
📄 CodeRabbit inference engine (.cursor/rules/react.mdc)
**/*.tsx
: Use proper type definitions for props and state
Leverage TypeScript's type inference where possible
Use proper event types for handlers
Implement proper generic types for reusable components
Use proper type guards for conditional rendering
Files:
packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx
packages/clerk-js/src/ui/elements/contexts/index.tsx
🧬 Code graph analysis (1)
packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx (4)
packages/clerk-js/src/ui/contexts/components/Plans.tsx (2)
useSubscription
(63-78)usePlans
(80-90)packages/shared/src/react/hooks/useSubscription.tsx (1)
useSubscription
(32-65)packages/shared/src/react/hooks/usePlans.tsx (1)
usePlans
(9-22)packages/clerk-js/src/ui/elements/contexts/index.tsx (1)
useFlowMetadata
(162-162)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
- GitHub Check: Formatting | Dedupe | Changeset
- GitHub Check: Build Packages
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: Analyze (javascript-typescript)
- GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (2)
packages/clerk-js/src/ui/elements/contexts/index.tsx (1)
128-134
: FlowMetadata context usage verified – all call sites updatedAll occurrences of
useFlowMetadata
in the repo compile and type-check against the extended shape. Call sites either consume the newrootElement
/setRootElement
properties or continue to use existing fields without error:• packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx (line 10):
DestructuressetRootElement
fromuseFlowMetadata()
• packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx (line 16):
DestructuresrootElement
fromuseFlowMetadata()
• packages/clerk-js/src/ui/elements/Card/CardRoot.tsx (line 14):
Assigns entireflowMetadata
object fromuseFlowMetadata()
• packages/clerk-js/src/ui/elements/Card/CardContent.tsx (line 22):
Assigns entireflowMetadata
object fromuseFlowMetadata()
• packages/clerk-js/src/ui/customizables/Flow.tsx (line 30):
Destructures existingflow
property fromuseFlowMetadata()
No other usages were found, and external packages won’t be impacted by the broader context shape.
packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx (1)
102-102
: Placement of SyncRootElement is goodRendering the readiness synchronizer immediately under Flow.Root ensures the root element exists early and avoids additional reflows. With the dependency fix above, this should reliably signal readiness.
function SyncRootElement() { | ||
const clerk = useClerk(); | ||
const { data: subscription, isLoading: isSubscriptionLoading } = useSubscription(); | ||
const { data: plans, isLoading: isPlansLoading } = usePlans(); | ||
const { rootElement } = useFlowMetadata(); | ||
|
||
useEffect(() => { | ||
if (isSubscriptionLoading || isPlansLoading) { | ||
return; | ||
} | ||
const isReady = clerk.isSignedIn ? !!subscription : plans.length > 0; | ||
|
||
if (isReady) { | ||
rootElement?.setAttribute('data-ready', 'true'); | ||
} | ||
}, [subscription, plans]); | ||
|
||
return null; | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
data-ready attribute may never be set due to missing rootElement in deps
If rootElement becomes available after the effect runs (likely, given it’s set via InvisibleRootBox), the effect won’t re-run and data-ready will never be set, keeping the fallback visible indefinitely. Also include clerk.isSignedIn and loading flags in deps.
Apply:
function SyncRootElement() {
const clerk = useClerk();
const { data: subscription, isLoading: isSubscriptionLoading } = useSubscription();
const { data: plans, isLoading: isPlansLoading } = usePlans();
const { rootElement } = useFlowMetadata();
useEffect(() => {
- if (isSubscriptionLoading || isPlansLoading) {
+ if (isSubscriptionLoading || isPlansLoading) {
return;
}
- const isReady = clerk.isSignedIn ? !!subscription : plans.length > 0;
+ const isReady = clerk.isSignedIn ? !!subscription : (plans?.length ?? 0) > 0;
if (isReady) {
rootElement?.setAttribute('data-ready', 'true');
}
- }, [subscription, plans]);
+ }, [rootElement, clerk.isSignedIn, isSubscriptionLoading, isPlansLoading, subscription, plans]);
return null;
}
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
function SyncRootElement() { | |
const clerk = useClerk(); | |
const { data: subscription, isLoading: isSubscriptionLoading } = useSubscription(); | |
const { data: plans, isLoading: isPlansLoading } = usePlans(); | |
const { rootElement } = useFlowMetadata(); | |
useEffect(() => { | |
if (isSubscriptionLoading || isPlansLoading) { | |
return; | |
} | |
const isReady = clerk.isSignedIn ? !!subscription : plans.length > 0; | |
if (isReady) { | |
rootElement?.setAttribute('data-ready', 'true'); | |
} | |
}, [subscription, plans]); | |
return null; | |
} | |
function SyncRootElement() { | |
const clerk = useClerk(); | |
const { data: subscription, isLoading: isSubscriptionLoading } = useSubscription(); | |
const { data: plans, isLoading: isPlansLoading } = usePlans(); | |
const { rootElement } = useFlowMetadata(); | |
useEffect(() => { | |
if (isSubscriptionLoading || isPlansLoading) { | |
return; | |
} | |
const isReady = clerk.isSignedIn | |
? !!subscription | |
: (plans?.length ?? 0) > 0; | |
if (isReady) { | |
rootElement?.setAttribute('data-ready', 'true'); | |
} | |
}, [ | |
rootElement, | |
clerk.isSignedIn, | |
isSubscriptionLoading, | |
isPlansLoading, | |
subscription, | |
plans, | |
]); | |
return null; | |
} |
🤖 Prompt for AI Agents
In packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx around
lines 12-30, the useEffect currently omits rootElement, clerk.isSignedIn,
isSubscriptionLoading and isPlansLoading from its dependency array so it may not
re-run when the rootElement becomes available or auth/loading state changes;
update the effect dependencies to include rootElement, clerk.isSignedIn,
isSubscriptionLoading and isPlansLoading (and keep subscription and plans),
ensure you guard rootElement with a null check before calling setAttribute, and
only set data-ready when isReady is true so the effect will re-run and correctly
set the attribute when rootElement appears or state changes.
b2ca731
to
31115ef
Compare
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/react/src/components/uiComponents.tsx (1)
580-585
: PricingTable now waits for readiness via attribute selector — good, but ensure the observer watches attribute mutationsPassing
{ selector: '[data-ready="true"]' }
is the right approach to avoid CLS by keeping the fallback visible until data is ready. However, the current waiter (waitForElementChildren) only observeschildList
mutations by default. If readiness is signaled solely by togglingdata-ready
(without child insertions), the hook may never transition to "rendered," leaving the fallback visible and the host element hidden.Please update the waiter to observe attribute changes (see suggested diff in
useWaitForComponentMount.ts
). Without that, this change risks a permanent "rendering" state when onlydata-ready
flips.
🧹 Nitpick comments (4)
packages/react/src/utils/useWaitForComponentMount.ts (4)
31-45
: Tighten observer/timeout lifecycle to prevent leaks and double-settle attempts
- Store the timeout id and clear it when resolving.
- Disconnect once resolved/rejected.
- Minor: re-querying
elementToWatch
only when null is fine; no change needed there.Apply:
- const observer = new MutationObserver(mutationsList => { + let timer: ReturnType<typeof setTimeout> | undefined; + const observer = new MutationObserver(mutationsList => { for (const mutation of mutationsList) { if (!elementToWatch && selector) { elementToWatch = root?.querySelector(selector); } if ( (globalOptions.childList && mutation.type === 'childList') || (globalOptions.attributes && mutation.type === 'attributes') ) { if (isReady(elementToWatch, selector)) { observer.disconnect(); - resolve(); + if (timer) { + clearTimeout(timer); + } + resolve(); return; } } } }); - observer.observe(root, globalOptions); + const { isReady: _isReady, ...observerOptions } = globalOptions; + observer.observe(root, observerOptions as MutationObserverInit); // Set up an optional timeout to reject the promise if the element never gets child nodes if (timeout > 0) { - setTimeout(() => { + timer = setTimeout(() => { observer.disconnect(); reject(new Error(`Timeout waiting for ${selector}`)); }, timeout); }Also applies to: 52-58
10-17
: SSR safety nit: avoid referencingdocument
in default parametersWhile this function is invoked client-side due to the
useEffect
guard, referencingdocument
in a default parameter can still surprise future callers. Prefer computing the default root inside the executor.Apply:
- return (options: { selector: string; root?: HTMLElement | null; timeout?: number }) => - new Promise<void>((resolve, reject) => { - const { root = document?.body, selector, timeout = 0 } = options; + return (options: { selector: string; root?: HTMLElement | null; timeout?: number }) => + new Promise<void>((resolve, reject) => { + const { selector, timeout = 0 } = options; + const root = options.root ?? (typeof document !== 'undefined' ? document.body : null);
68-75
: Update JSDoc to reflect new options and return typeThe hook now accepts an options object and returns a status union. Document these to keep the public API clear.
Apply:
/** * Detect when a Clerk component has mounted by watching DOM updates to an element with a `data-clerk-component="${component}"` property. */ -export function useWaitForComponentMount( +/** + * @param component The Clerk component name (e.g., "PricingTable"). + * @param options Optional readiness selector to further gate mount resolution (e.g., '[data-ready="true"]'). + * @returns 'rendering' | 'rendered' | 'error' + */ +export function useWaitForComponentMount(
83-91
: Minor: allow a timeout to surface as hook option for better failure modesRight now, a stalled readiness check leaves the UI in a permanent "rendering" state. Consider exposing a
timeoutMs
in the hook and mapping timeout tosetStatus('error')
with a meaningful message. I can draft this if desired.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (6)
.changeset/floppy-glasses-share.md
(1 hunks)packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
(2 hunks)packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx
(2 hunks)packages/clerk-js/src/ui/elements/contexts/index.tsx
(1 hunks)packages/react/src/components/uiComponents.tsx
(1 hunks)packages/react/src/utils/useWaitForComponentMount.ts
(2 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
- packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx
- .changeset/floppy-glasses-share.md
- packages/clerk-js/src/ui/elements/contexts/index.tsx
- packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
🧰 Additional context used
📓 Path-based instructions (8)
**/*.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
**/*.{js,jsx,ts,tsx}
: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels
Files:
packages/react/src/components/uiComponents.tsx
packages/react/src/utils/useWaitForComponentMount.ts
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Use Prettier for consistent code formatting
Files:
packages/react/src/components/uiComponents.tsx
packages/react/src/utils/useWaitForComponentMount.ts
packages/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/react/src/components/uiComponents.tsx
packages/react/src/utils/useWaitForComponentMount.ts
packages/**/*.{ts,tsx,d.ts}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Packages should export TypeScript types alongside runtime code
Files:
packages/react/src/components/uiComponents.tsx
packages/react/src/utils/useWaitForComponentMount.ts
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Use proper TypeScript error types
**/*.{ts,tsx}
: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoidany
type - preferunknown
when type is uncertain, then narrow with type guards
Useinterface
for object shapes that might be extended
Usetype
for unions, primitives, and computed types
Preferreadonly
properties for immutable data structures
Useprivate
for internal implementation details
Useprotected
for inheritance hierarchies
Usepublic
explicitly for clarity in public APIs
Preferreadonly
for properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Useconst assertions
for literal types:as const
Usesatisfies
operator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports:import type { ... } from ...
Noany
types without justification
Proper error handling with typed errors
Consistent use ofreadonly
for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)
Files:
packages/react/src/components/uiComponents.tsx
packages/react/src/utils/useWaitForComponentMount.ts
**/*.{jsx,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
**/*.{jsx,tsx}
: Use error boundaries in React components
Minimize re-renders in React components
**/*.{jsx,tsx}
: Always use functional components with hooks instead of class components
Follow PascalCase naming for components:UserProfile
,NavigationMenu
Keep components focused on a single responsibility - split large components
Limit component size to 150-200 lines; extract logic into custom hooks
Use composition over inheritance - prefer smaller, composable components
Export components as named exports for better tree-shaking
One component per file with matching filename and component name
Use useState for simple state management
Use useReducer for complex state logic
Implement proper state initialization
Use proper state updates with callbacks
Implement proper state cleanup
Use Context API for theme/authentication
Implement proper state selectors
Use proper state normalization
Implement proper state persistence
Use React.memo for expensive components
Implement proper useCallback for handlers
Use proper useMemo for expensive computations
Implement proper virtualization for lists
Use proper code splitting with React.lazy
Implement proper cleanup in useEffect
Use proper refs for DOM access
Implement proper event listener cleanup
Use proper abort controllers for fetch
Implement proper subscription cleanup
Use proper HTML elements
Implement proper ARIA attributes
Use proper heading hierarchy
Implement proper form labels
Use proper button types
Implement proper focus management
Use proper keyboard shortcuts
Implement proper tab order
Use proper skip links
Implement proper focus traps
Implement proper error boundaries
Use proper error logging
Implement proper error recovery
Use proper error messages
Implement proper error fallbacks
Use proper form validation
Implement proper error states
Use proper error messages
Implement proper form submission
Use proper form reset
Use proper component naming
Implement proper file naming
Use proper prop naming
Implement proper...
Files:
packages/react/src/components/uiComponents.tsx
**/*.{js,ts,tsx,jsx}
📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.
Files:
packages/react/src/components/uiComponents.tsx
packages/react/src/utils/useWaitForComponentMount.ts
**/*.tsx
📄 CodeRabbit inference engine (.cursor/rules/react.mdc)
**/*.tsx
: Use proper type definitions for props and state
Leverage TypeScript's type inference where possible
Use proper event types for handlers
Implement proper generic types for reusable components
Use proper type guards for conditional rendering
Files:
packages/react/src/components/uiComponents.tsx
🧬 Code graph analysis (1)
packages/react/src/components/uiComponents.tsx (1)
packages/react/src/utils/useWaitForComponentMount.ts (1)
useWaitForComponentMount
(71-102)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (19)
- GitHub Check: Integration Tests (nextjs, chrome, 15)
- GitHub Check: Integration Tests (machine, chrome)
- GitHub Check: Integration Tests (billing, chrome)
- GitHub Check: Integration Tests (tanstack-react-start, chrome)
- GitHub Check: Integration Tests (nextjs, chrome, 14)
- GitHub Check: Integration Tests (nuxt, chrome)
- GitHub Check: Integration Tests (astro, chrome)
- GitHub Check: Integration Tests (expo-web, chrome)
- GitHub Check: Integration Tests (vue, chrome)
- GitHub Check: Integration Tests (sessions, chrome)
- GitHub Check: Integration Tests (tanstack-react-router, chrome)
- GitHub Check: Integration Tests (react-router, chrome)
- GitHub Check: Integration Tests (ap-flows, chrome)
- GitHub Check: Integration Tests (elements, chrome)
- GitHub Check: Integration Tests (quickstart, chrome)
- GitHub Check: Integration Tests (localhost, chrome)
- GitHub Check: Integration Tests (generic, chrome)
- GitHub Check: Unit Tests (22, **)
- GitHub Check: Static analysis
🔇 Additional comments (1)
packages/react/src/utils/useWaitForComponentMount.ts (1)
78-99
: Re-initialization semantics whenselector
changesYou’ve added
options?.selector
to the deps, but the!watcherRef.current
guard prevents re-watching if the selector changes at runtime. If you intend the hook to react to selector changes, reset the ref in a cleanup. If selectors are static (preferred), ignore this.Apply:
useEffect(() => { if (!component) { throw new Error('Clerk: no component name provided, unable to detect mount.'); } if (typeof window !== 'undefined' && !watcherRef.current) { const defaultSelector = `[data-clerk-component="${component}"]`; const selector = options?.selector; watcherRef.current = waitForElementChildren({ selector: selector ? // Allows for `[data-clerk-component="xxxx"][data-some-attribute="123"] .my-class` defaultSelector + selector : defaultSelector, }) .then(() => { setStatus('rendered'); }) .catch(() => { setStatus('error'); }); } - }, [component, options?.selector]); + return () => { + watcherRef.current = undefined; + }; + }, [component, options?.selector]);Would you like this hook to handle dynamic selector changes, or are callers guaranteed to pass a stable selector?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx (1)
11-22
: Prevent CLS & ensure attribute cleanup in InvisibleRootBox• In
packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx
switch fromReact.useEffect
toReact.useLayoutEffect
so class and data-attribute mutations occur before paint.
• Add a dedicated cleanup effect to remove thedata-component-status
attribute on unmount, avoiding stale status on a reused host element.
• IncludeshowSpan
in the effect’s dependency list (or refactor to use a ref for a one-time mount check) to satisfyreact-hooks/exhaustive-deps
.
• Optional nit: namespace the data attribute (e.g.data-cl-component-status
) and update the selector inpackages/react/src/components/uiComponents.tsx
accordingly (selector: '[data-component-status="ready"]'
).Suggested diff:
--- a/packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx +++ b/packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx @@ -11,7 +11,7 @@ const _InvisibleRootBox = React.memo((props: RootBoxProps & { isFlowReady - React.useEffect(() => { + React.useLayoutEffect(() => { const parent = parentRef.current; if (!parent) { return; @@ -18,7 +18,7 @@ const _InvisibleRootBox = React.memo((props: RootBoxProps & { isFlowReady if (showSpan) { setShowSpan(false); } - parent.setAttribute('class', props.className); - parent.setAttribute('data-component-status', props.isFlowReady ? 'ready' : 'awaiting-data'); - }, [props.className, props.isFlowReady]); + parent.setAttribute('class', props.className); + parent.setAttribute('data-component-status', props.isFlowReady ? 'ready' : 'awaiting-data'); + }, [props.className, props.isFlowReady, showSpan]); + // Cleanup on unmount to avoid leaking stale status + React.useEffect(() => { + return () => { + const parent = parentRef.current; + if (parent) { + parent.removeAttribute('data-component-status'); + } + }; + }, []);If you rename the attribute to
data-cl-component-status
, update the matching selector in
packages/react/src/components/uiComponents.tsx
(line 582) toselector: '[data-cl-component-status="ready"]'
.
♻️ Duplicate comments (1)
packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx (1)
29-31
: Avoid stale parent ref across unmount; clear on component unmount, not on span removalWe need the parent element after the span disappears, so don’t null the ref here. Instead, clear it in an unmount cleanup (see previous comment). Minor readability tweak below makes the intent explicit.
Apply:
- ref={el => { - parentRef.current = el ? el.parentElement : parentRef.current; - }} + ref={el => { + if (el) { + parentRef.current = el.parentElement as HTMLElement | null; + } + }}
🧹 Nitpick comments (1)
packages/clerk-js/src/ui/customizables/Flow.tsx (1)
13-21
: Fold isFlowReady into FlowRootProps and document the new propSurfacing isFlowReady on Root looks good. To make the API cleaner and avoid the ad-hoc intersection at the callsite, consider adding isFlowReady directly to FlowRootProps. Also, if Flow.Root is part of the public surface, add a short JSDoc entry for the new prop.
Apply:
-type FlowRootProps = React.PropsWithChildren & FlowMetadata & { sx?: ThemableCssProp }; +type FlowRootProps = React.PropsWithChildren & FlowMetadata & { sx?: ThemableCssProp; isFlowReady?: boolean }; -const Root = (props: FlowRootProps & { isFlowReady?: boolean }) => { +const Root = (props: FlowRootProps) => {Please confirm that makeCustomizable(InvisibleRootBox) does not forward unknown props to DOM nodes. If it does, ensure isFlowReady is stripped before reaching any DOM element.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (5)
packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
(1 hunks)packages/clerk-js/src/ui/customizables/Flow.tsx
(1 hunks)packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx
(2 hunks)packages/clerk-js/src/ui/elements/contexts/index.tsx
(1 hunks)packages/react/src/components/uiComponents.tsx
(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
- packages/react/src/components/uiComponents.tsx
- packages/clerk-js/src/ui/elements/contexts/index.tsx
- packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
🧰 Additional context used
📓 Path-based instructions (9)
packages/clerk-js/src/ui/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/clerk-js-ui.mdc)
packages/clerk-js/src/ui/**/*.{ts,tsx}
: Element descriptors should always be camelCase
Use element descriptors in UI components to enable consistent theming and styling via appearance.elements
Element descriptors should generate unique, stable CSS classes for theming
Element descriptors should handle state classes (e.g., cl-loading, cl-active, cl-error, cl-open) automatically based on component state
Do not render hard-coded values; all user-facing strings must be localized using provided localization methods
Use the useLocalizations hook and localizationKeys utility for all text and error messages
Use the styled system (sx prop, theme tokens, responsive values) for custom component styling
Use useCardState for card-level state, useFormState for form-level state, and useLoadingStatus for loading states
Always use handleError utility for API errors and use translateError for localized error messages
Use useFormControl for form field state, implement proper validation, and handle loading and error states in forms
Use localization keys for all form labels and placeholders
Use element descriptors for consistent styling and follow the theme token system
Use the Card and FormContainer patterns for consistent UI structure
Files:
packages/clerk-js/src/ui/customizables/Flow.tsx
packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx
**/*.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
**/*.{js,jsx,ts,tsx}
: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels
Files:
packages/clerk-js/src/ui/customizables/Flow.tsx
packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Use Prettier for consistent code formatting
Files:
packages/clerk-js/src/ui/customizables/Flow.tsx
packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx
packages/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/clerk-js/src/ui/customizables/Flow.tsx
packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx
packages/**/*.{ts,tsx,d.ts}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Packages should export TypeScript types alongside runtime code
Files:
packages/clerk-js/src/ui/customizables/Flow.tsx
packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Use proper TypeScript error types
**/*.{ts,tsx}
: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoidany
type - preferunknown
when type is uncertain, then narrow with type guards
Useinterface
for object shapes that might be extended
Usetype
for unions, primitives, and computed types
Preferreadonly
properties for immutable data structures
Useprivate
for internal implementation details
Useprotected
for inheritance hierarchies
Usepublic
explicitly for clarity in public APIs
Preferreadonly
for properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Useconst assertions
for literal types:as const
Usesatisfies
operator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports:import type { ... } from ...
Noany
types without justification
Proper error handling with typed errors
Consistent use ofreadonly
for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)
Files:
packages/clerk-js/src/ui/customizables/Flow.tsx
packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx
**/*.{jsx,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
**/*.{jsx,tsx}
: Use error boundaries in React components
Minimize re-renders in React components
**/*.{jsx,tsx}
: Always use functional components with hooks instead of class components
Follow PascalCase naming for components:UserProfile
,NavigationMenu
Keep components focused on a single responsibility - split large components
Limit component size to 150-200 lines; extract logic into custom hooks
Use composition over inheritance - prefer smaller, composable components
Export components as named exports for better tree-shaking
One component per file with matching filename and component name
Use useState for simple state management
Use useReducer for complex state logic
Implement proper state initialization
Use proper state updates with callbacks
Implement proper state cleanup
Use Context API for theme/authentication
Implement proper state selectors
Use proper state normalization
Implement proper state persistence
Use React.memo for expensive components
Implement proper useCallback for handlers
Use proper useMemo for expensive computations
Implement proper virtualization for lists
Use proper code splitting with React.lazy
Implement proper cleanup in useEffect
Use proper refs for DOM access
Implement proper event listener cleanup
Use proper abort controllers for fetch
Implement proper subscription cleanup
Use proper HTML elements
Implement proper ARIA attributes
Use proper heading hierarchy
Implement proper form labels
Use proper button types
Implement proper focus management
Use proper keyboard shortcuts
Implement proper tab order
Use proper skip links
Implement proper focus traps
Implement proper error boundaries
Use proper error logging
Implement proper error recovery
Use proper error messages
Implement proper error fallbacks
Use proper form validation
Implement proper error states
Use proper error messages
Implement proper form submission
Use proper form reset
Use proper component naming
Implement proper file naming
Use proper prop naming
Implement proper...
Files:
packages/clerk-js/src/ui/customizables/Flow.tsx
packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx
**/*.{js,ts,tsx,jsx}
📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.
Files:
packages/clerk-js/src/ui/customizables/Flow.tsx
packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx
**/*.tsx
📄 CodeRabbit inference engine (.cursor/rules/react.mdc)
**/*.tsx
: Use proper type definitions for props and state
Leverage TypeScript's type inference where possible
Use proper event types for handlers
Implement proper generic types for reusable components
Use proper type guards for conditional rendering
Files:
packages/clerk-js/src/ui/customizables/Flow.tsx
packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
- GitHub Check: Formatting | Dedupe | Changeset
- GitHub Check: Build Packages
- GitHub Check: semgrep/ci
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (1)
packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx (1)
7-7
: Prop surface widened to include isFlowReady — LGTMTyping aligns with the new readiness signal and matches how Flow.Root forwards the prop.
Co-authored-by: Bryce Kalow <[email protected]>
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Nitpick comments (1)
packages/react/src/components/uiComponents.tsx (1)
584-585
: Keep fallback visible on error to avoid CLS regressionsIf the waiter fails (status === 'error'), we currently hide the fallback. Safer to show fallback until explicitly 'rendered'.
Apply:
- const shouldShowFallback = mountingStatus === 'rendering' || !clerk.loaded; + const shouldShowFallback = mountingStatus !== 'rendered' || !clerk.loaded;
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (2)
packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx
(2 hunks)packages/react/src/components/uiComponents.tsx
(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx
🧰 Additional context used
📓 Path-based instructions (8)
**/*.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
**/*.{js,jsx,ts,tsx}
: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels
Files:
packages/react/src/components/uiComponents.tsx
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Use Prettier for consistent code formatting
Files:
packages/react/src/components/uiComponents.tsx
packages/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/react/src/components/uiComponents.tsx
packages/**/*.{ts,tsx,d.ts}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Packages should export TypeScript types alongside runtime code
Files:
packages/react/src/components/uiComponents.tsx
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Use proper TypeScript error types
**/*.{ts,tsx}
: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoidany
type - preferunknown
when type is uncertain, then narrow with type guards
Useinterface
for object shapes that might be extended
Usetype
for unions, primitives, and computed types
Preferreadonly
properties for immutable data structures
Useprivate
for internal implementation details
Useprotected
for inheritance hierarchies
Usepublic
explicitly for clarity in public APIs
Preferreadonly
for properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Useconst assertions
for literal types:as const
Usesatisfies
operator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports:import type { ... } from ...
Noany
types without justification
Proper error handling with typed errors
Consistent use ofreadonly
for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)
Files:
packages/react/src/components/uiComponents.tsx
**/*.{jsx,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
**/*.{jsx,tsx}
: Use error boundaries in React components
Minimize re-renders in React components
**/*.{jsx,tsx}
: Always use functional components with hooks instead of class components
Follow PascalCase naming for components:UserProfile
,NavigationMenu
Keep components focused on a single responsibility - split large components
Limit component size to 150-200 lines; extract logic into custom hooks
Use composition over inheritance - prefer smaller, composable components
Export components as named exports for better tree-shaking
One component per file with matching filename and component name
Use useState for simple state management
Use useReducer for complex state logic
Implement proper state initialization
Use proper state updates with callbacks
Implement proper state cleanup
Use Context API for theme/authentication
Implement proper state selectors
Use proper state normalization
Implement proper state persistence
Use React.memo for expensive components
Implement proper useCallback for handlers
Use proper useMemo for expensive computations
Implement proper virtualization for lists
Use proper code splitting with React.lazy
Implement proper cleanup in useEffect
Use proper refs for DOM access
Implement proper event listener cleanup
Use proper abort controllers for fetch
Implement proper subscription cleanup
Use proper HTML elements
Implement proper ARIA attributes
Use proper heading hierarchy
Implement proper form labels
Use proper button types
Implement proper focus management
Use proper keyboard shortcuts
Implement proper tab order
Use proper skip links
Implement proper focus traps
Implement proper error boundaries
Use proper error logging
Implement proper error recovery
Use proper error messages
Implement proper error fallbacks
Use proper form validation
Implement proper error states
Use proper error messages
Implement proper form submission
Use proper form reset
Use proper component naming
Implement proper file naming
Use proper prop naming
Implement proper...
Files:
packages/react/src/components/uiComponents.tsx
**/*.{js,ts,tsx,jsx}
📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.
Files:
packages/react/src/components/uiComponents.tsx
**/*.tsx
📄 CodeRabbit inference engine (.cursor/rules/react.mdc)
**/*.tsx
: Use proper type definitions for props and state
Leverage TypeScript's type inference where possible
Use proper event types for handlers
Implement proper generic types for reusable components
Use proper type guards for conditional rendering
Files:
packages/react/src/components/uiComponents.tsx
🧬 Code graph analysis (1)
packages/react/src/components/uiComponents.tsx (1)
packages/react/src/utils/useWaitForComponentMount.ts (1)
useWaitForComponentMount
(71-102)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (23)
- GitHub Check: Integration Tests (nextjs, chrome, 14)
- GitHub Check: Integration Tests (nextjs, chrome, 15)
- GitHub Check: Integration Tests (nuxt, chrome)
- GitHub Check: Integration Tests (machine, chrome)
- GitHub Check: Integration Tests (react-router, chrome)
- GitHub Check: Integration Tests (billing, chrome)
- GitHub Check: Integration Tests (astro, chrome)
- GitHub Check: Integration Tests (vue, chrome)
- GitHub Check: Integration Tests (tanstack-react-start, chrome)
- GitHub Check: Integration Tests (localhost, chrome)
- GitHub Check: Integration Tests (elements, chrome)
- GitHub Check: Integration Tests (expo-web, chrome)
- GitHub Check: Integration Tests (generic, chrome)
- GitHub Check: Integration Tests (tanstack-react-router, chrome)
- GitHub Check: Integration Tests (ap-flows, chrome)
- GitHub Check: Integration Tests (sessions, chrome)
- GitHub Check: Integration Tests (express, chrome)
- GitHub Check: Integration Tests (quickstart, chrome)
- GitHub Check: Publish with pkg-pr-new
- GitHub Check: Unit Tests (22, **)
- GitHub Check: Unit Tests (18, --filter=@clerk/astro --filter=@clerk/backend --filter=@clerk/express --filter=@c...
- GitHub Check: Static analysis
- GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (1)
packages/react/src/components/uiComponents.tsx (1)
580-583
: Approve selector: no change needed
Thedata-component-status
attribute is applied on the same element that carries thedata-clerk-component
attribute, so concatenatingdefaultSelector + selector
(i.e.[data-clerk-component="PricingTable"][data-component-status="ready"]
) will correctly match that root node.
selector: selector | ||
? // Allows for `[data-clerk-component="xxxx"][data-some-attribute="123"] .my-class` | ||
defaultSelector + selector | ||
: defaultSelector, |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
do we need to join with a ' '
? Or intentionally not?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The concatenation happens between [data-clerk-component="xxxx"]
and [data-some-attribute="123"] .my-class
, and between those there is no space.
Description
<PricingTable/>
is one of the few components that accepts thefallback
prop and that its initial data are loaded asynchronously after clerk.js has loaded. We need to wait for that plans to be resolved and only then swap the fallback with the content.@clerk/clerk-react
version with an older clerk-js version (probably pinned) the component that you pass in the fallback prop will be visible indefinitely.Before
Screen.Recording.2025-08-27.at.12.04.27.AM.mov
After
Screen.Recording.2025-08-27.at.12.03.17.AM.mov
Checklist
pnpm test
runs as expected.pnpm build
runs as expected.Type of change
Summary by CodeRabbit
Bug Fixes
Chores