-
Notifications
You must be signed in to change notification settings - Fork 402
poc: useAuth with uSES #7170
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?
poc: useAuth with uSES #7170
Conversation
|
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
WalkthroughThese changes introduce a new external authentication state store ( Changes
Sequence Diagram(s)sequenceDiagram
participant App as Application
participant CCP as ClerkContextProvider
participant useAuth as useAuth Hook
participant Store as authStore
participant Clerk as IsomorphicClerk
Note over CCP: SSR/Hydration Setup
CCP->>Store: setServerSnapshot(initialState)
CCP->>Store: connect(clerk)
Store->>Clerk: subscribe to updates
Note over CCP: Render Phase
CCP->>Store: useSyncExternalStore listener
Store-->>CCP: getSnapshot() / getServerSnapshot()
App->>useAuth: useAuth()
useAuth->>Store: useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot)
Store-->>useAuth: authValue snapshot
useAuth-->>App: { userId, sessionId, session, user, ... }
Clerk->>Store: update event
Store->>Store: transformClerkState()
Store->>Store: notifyListeners()
Store-->>useAuth: new snapshot
useAuth->>App: re-render with updated auth
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
Comment |
| if (authContext.sessionId === undefined && authContext.userId === undefined) { | ||
| authContext = initialAuthState != null ? initialAuthState : {}; | ||
| } |
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.
No need to see if we can trust the authContext. We can just the the authStore directly here
@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: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
packages/react/src/contexts/ClerkContextProvider.tsx (1)
104-128: Remove unusedclerkStatusstate to prevent unnecessary re-renders.The
clerkStatusstate is maintained and returned but never used (line 28 only destructuresisomorphicClerk). This causes unnecessary re-renders whenever clerk status changes.Apply this diff:
const useLoadedIsomorphicClerk = (options: IsomorphicClerkOptions) => { const isomorphicClerkRef = React.useRef(IsomorphicClerk.getOrCreateInstance(options)); - const [clerkStatus, setClerkStatus] = React.useState(isomorphicClerkRef.current.status); React.useEffect(() => { void isomorphicClerkRef.current.__unstable__updateProps({ appearance: options.appearance }); }, [options.appearance]); React.useEffect(() => { void isomorphicClerkRef.current.__unstable__updateProps({ options }); }, [options]); React.useEffect(() => { const clerk = isomorphicClerkRef.current; - clerk.on('status', setClerkStatus); return () => { - if (clerk) { - clerk.off('status', setClerkStatus); - } IsomorphicClerk.clearInstance(); }; }, []); - return { isomorphicClerk: isomorphicClerkRef.current, clerkStatus }; + return { isomorphicClerk: isomorphicClerkRef.current }; };packages/react/src/hooks/__tests__/useAuth.test.tsx (1)
99-109: Remove the skipped test or rewrite it to align with the newauthStorepattern.This test predates the refactoring to use
useSyncExternalStorewith an external store. The implementation (line 102 of useAuth.ts) now retrieves auth state directly fromauthStoreviauseSyncExternalStore, making manual context provider wrapping obsolete. Either remove this test entirely since the error-handling case is already validated by the first test, or rewrite it to verify the hook works correctly whenauthStoreis properly initialized—though note that testinguseSyncExternalStoreintegration typically requires full provider setup rather than component wrapping.Also note: The test mock uses non-standard method names (
getClientSnapshot,getServerSnapshot) that don't match the actual store interface (getSnapshot,getServerSnapshot).
🧹 Nitpick comments (1)
packages/react/src/stores/authStore.ts (1)
8-8: Use theListenertype alias consistently.Line 5 defines
type Listener = () => void;but line 8 declareslistenerswith the inline type. For consistency and maintainability, use the type alias.Apply this diff:
- private listeners = new Set<() => void>(); + private listeners = new Set<Listener>();
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Disabled knowledge base sources:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (6)
packages/react/src/contexts/AuthContext.ts(1 hunks)packages/react/src/contexts/ClerkContextProvider.tsx(4 hunks)packages/react/src/hooks/__tests__/useAuth.test.tsx(2 hunks)packages/react/src/hooks/useAuth.ts(2 hunks)packages/react/src/stores/authStore.ts(1 hunks)packages/shared/src/authorization.ts(3 hunks)
🧰 Additional context used
📓 Path-based instructions (11)
**/*.{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/hooks/__tests__/useAuth.test.tsxpackages/shared/src/authorization.tspackages/react/src/stores/authStore.tspackages/react/src/hooks/useAuth.tspackages/react/src/contexts/ClerkContextProvider.tsxpackages/react/src/contexts/AuthContext.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/hooks/__tests__/useAuth.test.tsxpackages/shared/src/authorization.tspackages/react/src/stores/authStore.tspackages/react/src/hooks/useAuth.tspackages/react/src/contexts/ClerkContextProvider.tsxpackages/react/src/contexts/AuthContext.ts
packages/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/react/src/hooks/__tests__/useAuth.test.tsxpackages/shared/src/authorization.tspackages/react/src/stores/authStore.tspackages/react/src/hooks/useAuth.tspackages/react/src/contexts/ClerkContextProvider.tsxpackages/react/src/contexts/AuthContext.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/hooks/__tests__/useAuth.test.tsxpackages/shared/src/authorization.tspackages/react/src/stores/authStore.tspackages/react/src/hooks/useAuth.tspackages/react/src/contexts/ClerkContextProvider.tsxpackages/react/src/contexts/AuthContext.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
Avoidanytype - preferunknownwhen type is uncertain, then narrow with type guards
Useinterfacefor object shapes that might be extended
Usetypefor unions, primitives, and computed types
Preferreadonlyproperties for immutable data structures
Useprivatefor internal implementation details
Useprotectedfor inheritance hierarchies
Usepublicexplicitly for clarity in public APIs
Preferreadonlyfor 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 assertionsfor literal types:as const
Usesatisfiesoperator 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 ...
Noanytypes without justification
Proper error handling with typed errors
Consistent use ofreadonlyfor 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/hooks/__tests__/useAuth.test.tsxpackages/shared/src/authorization.tspackages/react/src/stores/authStore.tspackages/react/src/hooks/useAuth.tspackages/react/src/contexts/ClerkContextProvider.tsxpackages/react/src/contexts/AuthContext.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/hooks/__tests__/useAuth.test.tsxpackages/react/src/contexts/ClerkContextProvider.tsx
packages/**/*.{test,spec}.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Unit tests should use Jest or Vitest as the test runner.
Files:
packages/react/src/hooks/__tests__/useAuth.test.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/hooks/__tests__/useAuth.test.tsxpackages/shared/src/authorization.tspackages/react/src/stores/authStore.tspackages/react/src/hooks/useAuth.tspackages/react/src/contexts/ClerkContextProvider.tsxpackages/react/src/contexts/AuthContext.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/hooks/__tests__/useAuth.test.tsxpackages/react/src/contexts/ClerkContextProvider.tsx
**/*.test.{jsx,tsx}
📄 CodeRabbit inference engine (.cursor/rules/react.mdc)
**/*.test.{jsx,tsx}: Use React Testing Library
Test component behavior, not implementation
Use proper test queries
Implement proper test isolation
Use proper test coverage
Test component interactions
Use proper test data
Implement proper test setup
Use proper test cleanup
Implement proper test assertions
Use proper test structure
Files:
packages/react/src/hooks/__tests__/useAuth.test.tsx
**/__tests__/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/typescript.mdc)
**/__tests__/**/*.{ts,tsx}: Create type-safe test builders/factories
Use branded types for test isolation
Implement proper mock types that match interfaces
Files:
packages/react/src/hooks/__tests__/useAuth.test.tsx
🧬 Code graph analysis (3)
packages/react/src/stores/authStore.ts (1)
packages/react/src/contexts/AuthContext.ts (1)
AuthContextValue(10-21)
packages/react/src/hooks/useAuth.ts (1)
packages/react/src/stores/authStore.ts (1)
authStore(113-113)
packages/react/src/contexts/ClerkContextProvider.tsx (3)
packages/shared/src/deriveState.ts (1)
deriveState(15-20)packages/react/src/stores/authStore.ts (1)
authStore(113-113)packages/react/src/isomorphicClerk.ts (3)
session(695-701)user(703-709)organization(711-717)
⏰ 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). (27)
- GitHub Check: Integration Tests (quickstart, chrome, 16)
- GitHub Check: Integration Tests (nextjs, chrome, 14)
- GitHub Check: Integration Tests (nextjs, chrome, 15)
- GitHub Check: Integration Tests (custom, chrome)
- GitHub Check: Integration Tests (quickstart, chrome, 15)
- GitHub Check: Integration Tests (nextjs, chrome, 16)
- GitHub Check: Integration Tests (react-router, chrome)
- GitHub Check: Integration Tests (billing, chrome)
- GitHub Check: Integration Tests (machine, chrome)
- GitHub Check: Integration Tests (tanstack-react-start, chrome)
- GitHub Check: Integration Tests (handshake, chrome)
- GitHub Check: Integration Tests (nuxt, chrome)
- GitHub Check: Integration Tests (sessions, chrome)
- GitHub Check: Integration Tests (localhost, chrome)
- GitHub Check: Integration Tests (vue, chrome)
- GitHub Check: Integration Tests (expo-web, chrome)
- GitHub Check: Integration Tests (astro, chrome)
- GitHub Check: Integration Tests (handshake:staging, chrome)
- GitHub Check: Integration Tests (sessions:staging, chrome)
- GitHub Check: Integration Tests (elements, chrome)
- GitHub Check: Integration Tests (ap-flows, chrome)
- GitHub Check: Integration Tests (generic, chrome)
- GitHub Check: Integration Tests (express, chrome)
- GitHub Check: Unit Tests (22, **)
- GitHub Check: Publish with pkg-pr-new
- GitHub Check: Static analysis
- GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (9)
packages/shared/src/authorization.ts (1)
78-78: Non-functional JSDoc formatting improvements.The blank-line asterisks in the JSDoc blocks (lines 78, 166, 242) improve readability by separating description paragraphs. These changes are consistent with the broader documentation improvements mentioned in the PR context and align with JSDoc style best practices.
Also applies to: 166-166, 242-242
packages/react/src/hooks/__tests__/useAuth.test.tsx (1)
27-55: LGTM! Mock structure aligns with useSyncExternalStore pattern.The mock correctly provides
getClientSnapshot,getServerSnapshot, andsubscribemethods expected byuseSyncExternalStore. Returning identical snapshots for client and server is appropriate for these tests.packages/react/src/stores/authStore.ts (2)
17-32: LGTM! Lifecycle methods correctly handle subscription management.The
connectmethod safely handles multiple calls by disconnecting first, and immediately syncs state withupdateFromClerk. Thedisconnectmethod properly cleans up the subscription.
73-111: LGTM! State transformation correctly handles optional properties.The
transformClerkStatemethod safely accesses optional Clerk properties using optional chaining, and correctly derives organization membership data. The nullish coalescing forfactorVerificationAgeensures a consistentnulldefault.packages/react/src/hooks/useAuth.ts (2)
95-119: LGTM! Correctly implements external store pattern for SSR hydration.The hook now derives authentication state from
authStoreusinguseSyncExternalStore, which properly handles SSR and client-side hydration. This addresses the past review comment about trusting the auth context by using the store directly as the source of truth.Based on past review comments.
23-23: Remove| nullfromUseAuthOptionstype definition or document its purpose.No usages of
useAuth(null)exist in the codebase. The parameter is handled identically for bothnullandundefinedvia the nullish coalescing operator (initialAuthStateOrOptions ?? {}), making the| nullunion member redundant. Modern React hooks use onlyundefinedfor optional parameters. If this was added for backward compatibility, consider documenting it; otherwise, remove it to align with React conventions and simplify the type.packages/react/src/contexts/AuthContext.ts (1)
10-21: LGTM! Interface expanded to support enhanced auth state.The new
factorVerificationAgeandorgPermissionsfields align with the authentication state managed byauthStore. Field reordering doesn't affect functionality.packages/react/src/contexts/ClerkContextProvider.tsx (2)
46-67: LGTM! SSR hydration correctly initializes authStore.The
useLayoutEffectproperly:
- Sets the server snapshot before hydration when
initialStateis present- Connects the store to Clerk for live updates
- Cleans up the subscription on unmount
This ensures consistent auth state during SSR → CSR transition.
69-79: LGTM! Client-side auth state correctly synchronized with external store.Using
useSyncExternalStoreensures consistent auth state across SSR/hydration/client transitions, and all context values are properly memoized to prevent unnecessary re-renders.
| setServerSnapshot(snapshot: AuthSnapshot) { | ||
| this.serverSnapshot = snapshot; | ||
| } | ||
|
|
||
| /** | ||
| * For useSyncExternalStore - returns current client state | ||
| */ | ||
| getSnapshot = (): AuthSnapshot => { | ||
| return this.currentSnapshot; | ||
| }; | ||
|
|
||
| /** | ||
| * For useSyncExternalStore - returns SSR/hydration state | ||
| * React automatically uses this during SSR and hydration | ||
| */ | ||
| getServerSnapshot = (): AuthSnapshot => { | ||
| // If we have a server snapshot, ALWAYS return it | ||
| // React will switch to getSnapshot after hydration | ||
| return this.serverSnapshot || this.currentSnapshot; | ||
| }; |
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.
🛠️ Refactor suggestion | 🟠 Major
Add explicit return types to public methods.
Per coding guidelines, public API methods should have explicit return types. While TypeScript can infer these, explicit annotations improve maintainability and API documentation.
Apply this diff:
- setServerSnapshot(snapshot: AuthSnapshot) {
+ setServerSnapshot(snapshot: AuthSnapshot): void {
this.serverSnapshot = snapshot;
}
- getSnapshot = (): AuthSnapshot => {
+ getSnapshot = (): Readonly<AuthSnapshot> => {
return this.currentSnapshot;
};
- getServerSnapshot = (): AuthSnapshot => {
+ getServerSnapshot = (): Readonly<AuthSnapshot> => {
return this.serverSnapshot || this.currentSnapshot;
};Note: Consider returning Readonly<AuthSnapshot> to prevent consumers from mutating the snapshot directly.
📝 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.
| setServerSnapshot(snapshot: AuthSnapshot) { | |
| this.serverSnapshot = snapshot; | |
| } | |
| /** | |
| * For useSyncExternalStore - returns current client state | |
| */ | |
| getSnapshot = (): AuthSnapshot => { | |
| return this.currentSnapshot; | |
| }; | |
| /** | |
| * For useSyncExternalStore - returns SSR/hydration state | |
| * React automatically uses this during SSR and hydration | |
| */ | |
| getServerSnapshot = (): AuthSnapshot => { | |
| // If we have a server snapshot, ALWAYS return it | |
| // React will switch to getSnapshot after hydration | |
| return this.serverSnapshot || this.currentSnapshot; | |
| }; | |
| setServerSnapshot(snapshot: AuthSnapshot): void { | |
| this.serverSnapshot = snapshot; | |
| } | |
| /** | |
| * For useSyncExternalStore - returns current client state | |
| */ | |
| getSnapshot = (): Readonly<AuthSnapshot> => { | |
| return this.currentSnapshot; | |
| }; | |
| /** | |
| * For useSyncExternalStore - returns SSR/hydration state | |
| * React automatically uses this during SSR and hydration | |
| */ | |
| getServerSnapshot = (): Readonly<AuthSnapshot> => { | |
| // If we have a server snapshot, ALWAYS return it | |
| // React will switch to getSnapshot after hydration | |
| return this.serverSnapshot || this.currentSnapshot; | |
| }; |
🤖 Prompt for AI Agents
In packages/react/src/stores/authStore.ts around lines 37 to 56, the public
methods getSnapshot, getServerSnapshot and setServerSnapshot lack explicit
return type annotations; update their signatures to include explicit return
types (use Readonly<AuthSnapshot> for getters and void for the setter) so the
public API is typed explicitly and prevents consumers from mutating the returned
snapshot.
| private updateFromClerk(clerk: IsomorphicClerk) { | ||
| const newSnapshot = this.transformClerkState(clerk); | ||
|
|
||
| // Only notify if actually changed (reference equality is fine here) | ||
| if (newSnapshot !== this.currentSnapshot) { | ||
| this.currentSnapshot = newSnapshot; | ||
| this.notifyListeners(); | ||
| } | ||
| } |
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.
Reference equality check always fails—listeners notified on every update.
Line 67 checks newSnapshot !== this.currentSnapshot, but transformClerkState always creates a new object (line 64), so reference equality will always fail. This causes listeners to be notified on every Clerk update, even when auth state hasn't changed, leading to unnecessary re-renders.
Implement shallow equality checking to only notify when actual values change:
+ private hasChanged(prev: AuthSnapshot, next: AuthSnapshot): boolean {
+ return (
+ prev.actor !== next.actor ||
+ prev.factorVerificationAge !== next.factorVerificationAge ||
+ prev.orgId !== next.orgId ||
+ prev.orgPermissions !== next.orgPermissions ||
+ prev.orgRole !== next.orgRole ||
+ prev.orgSlug !== next.orgSlug ||
+ prev.sessionClaims !== next.sessionClaims ||
+ prev.sessionId !== next.sessionId ||
+ prev.sessionStatus !== next.sessionStatus ||
+ prev.userId !== next.userId
+ );
+ }
+
private updateFromClerk(clerk: IsomorphicClerk): void {
const newSnapshot = this.transformClerkState(clerk);
- if (newSnapshot !== this.currentSnapshot) {
+ if (this.hasChanged(this.currentSnapshot, newSnapshot)) {
this.currentSnapshot = newSnapshot;
this.notifyListeners();
}
}📝 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.
| private updateFromClerk(clerk: IsomorphicClerk) { | |
| const newSnapshot = this.transformClerkState(clerk); | |
| // Only notify if actually changed (reference equality is fine here) | |
| if (newSnapshot !== this.currentSnapshot) { | |
| this.currentSnapshot = newSnapshot; | |
| this.notifyListeners(); | |
| } | |
| } | |
| private hasChanged(prev: AuthSnapshot, next: AuthSnapshot): boolean { | |
| return ( | |
| prev.actor !== next.actor || | |
| prev.factorVerificationAge !== next.factorVerificationAge || | |
| prev.orgId !== next.orgId || | |
| prev.orgPermissions !== next.orgPermissions || | |
| prev.orgRole !== next.orgRole || | |
| prev.orgSlug !== next.orgSlug || | |
| prev.sessionClaims !== next.sessionClaims || | |
| prev.sessionId !== next.sessionId || | |
| prev.sessionStatus !== next.sessionStatus || | |
| prev.userId !== next.userId | |
| ); | |
| } | |
| private updateFromClerk(clerk: IsomorphicClerk): void { | |
| const newSnapshot = this.transformClerkState(clerk); | |
| // Only notify if actually changed (reference equality is fine here) | |
| if (this.hasChanged(this.currentSnapshot, newSnapshot)) { | |
| this.currentSnapshot = newSnapshot; | |
| this.notifyListeners(); | |
| } | |
| } |
🤖 Prompt for AI Agents
In packages/react/src/stores/authStore.ts around lines 63 to 71, the current
reference equality check always fails because transformClerkState creates a new
object each call, causing listeners to be notified on every update; replace the
reference check with a shallow equality comparison of the snapshot's top-level
properties (compare primitives and object references for the same keys) and only
assign this.currentSnapshot and call notifyListeners if the shallow comparison
detects any differences; either reuse an existing shallowEqual utility or add a
small helper here that iterates keys and compares values, then use its result
instead of !==.
|
Found 61 test failures on Blacksmith runners:
|
Description
POC of useSyncExternalStore in useAuth to get around hydration mismatches on initial SSR -> CSR transfer
Checklist
pnpm testruns as expected.pnpm buildruns as expected.Type of change
Summary by CodeRabbit
New Features
Refactor