Skip to content

feat: add useAuth0Suspense hook for handling auth loading state with React 19+ - #1184

Open
gyaneshgouraw-okta wants to merge 3 commits into
mainfrom
auth0-suspense
Open

feat: add useAuth0Suspense hook for handling auth loading state with React 19+#1184
gyaneshgouraw-okta wants to merge 3 commits into
mainfrom
auth0-suspense

Conversation

@gyaneshgouraw-okta

@gyaneshgouraw-okta gyaneshgouraw-okta commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

Summary

Adds useAuth0Suspense, a React 19-only hook that lets components read auth state declaratively: a <Suspense> boundary handles the loading state and a React Error Boundary handles initialization errors, removing the manual isLoading checks that useAuth0 requires.
The change is additive and non-breaking, the core path (Auth0Provider, useAuth0) stays compatible with React 16.11–19, peerDependencies is unchanged, and the new hook is gated at runtime so React 16–18 consumers get a clear error instead of a crash if they call it.

Changes

  • Auth0Provider now creates a stable initialization promise that resolves when auth init succeeds and rejects (with the same error surfaced on error) when it fails, exposed as an internal, unsupported context field.
  • New useAuth0Suspense() hook reads that promise via React 19's use(): it suspends until auth is ready (so the nearest <Suspense> fallback renders) and re-throws init errors to the nearest Error Boundary.
  • Returns the full useAuth0 interface minus isLoading (always resolved) and error (thrown), including all auth methods (loginWithRedirect, logout, getAccessTokenSilently, …).
  • Runtime guards: throws a clear "requires React 19" error when React.use is unavailable, and a "must be used within an <Auth0Provider>" error when used outside a provider.
  • Exported from the package root alongside its Auth0SuspenseContextInterface type.
  • Documented with a Suspense usage example in the examples doc.

Example

import { Suspense } from 'react';
import { Auth0Provider, useAuth0Suspense } from '@auth0/auth0-react';

function App() {
  return (
    <Auth0Provider domain={domain} clientId={clientId} authorizationParams={{ redirect_uri: window.location.origin }}>
      <MyErrorBoundary fallback={<p>Could not sign you in.</p>}>
        <Suspense fallback={<p>Loading…</p>}>
          <UserGreeting />
        </Suspense>
      </MyErrorBoundary>
    </Auth0Provider>
  );
}

function UserGreeting() {
  const { user, isAuthenticated } = useAuth0Suspense();
  return isAuthenticated ? <p>Hello, {user?.name}!</p> : <p>Please log in</p>;
}

Testing

  • npm test - full suite passing at 100% coverage.
  • New tests cover the hook's full behavior, its two success/pending render paths, both init-error paths routing to an Error Boundary, both runtime guards, and its export surface
  • Existing Auth0Provider tests extended to verify the init promise resolves on success, rejects on failure, and keeps a stable reference across re-renders.

@gyaneshgouraw-okta
gyaneshgouraw-okta requested a review from a team as a code owner July 29, 2026 08:34
@coderabbitai

coderabbitai Bot commented Jul 29, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Auth0Provider now exposes an internal initialization promise. The new React 19 useAuth0Suspense hook uses it to suspend during initialization and propagate failures to error boundaries. Tests and documentation cover the hook, exports, compatibility checks, and usage.

Changes

Auth0 Suspense integration

Layer / File(s) Summary
Initialization promise
src/auth0-context.tsx, src/auth0-provider.tsx, __tests__/auth-provider.test.tsx
Auth0Provider exposes a stable _initPromise that resolves after successful initialization and rejects when initialization fails.
Suspense hook and exports
src/use-auth0-suspense.tsx, src/index.tsx
useAuth0Suspense validates React 19 and provider usage, suspends on initialization, propagates initialization errors, retains error, omits isLoading and _initPromise, and is exported from the package root.
Behavior tests and documentation
__tests__/use-auth0-suspense.test.tsx, EXAMPLES.md
Tests cover pending and successful initialization, initialization failures, provider and React version errors, returned properties, and exports. Documentation adds a React 19 usage example.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Suggested reviewers: yogeshchoudhary147

Sequence Diagram(s)

sequenceDiagram
  participant Application
  participant Auth0Provider
  participant Auth0Client
  participant useAuth0Suspense
  participant Suspense
  participant ErrorBoundary

  Application->>Auth0Provider: render application
  Auth0Provider->>Auth0Client: initialize Auth0
  Application->>useAuth0Suspense: read authentication context
  useAuth0Suspense->>Auth0Provider: read _initPromise
  useAuth0Suspense-->>Suspense: suspend while initialization is pending
  Auth0Client-->>Auth0Provider: resolve or reject initialization
  Auth0Provider-->>useAuth0Suspense: provide initialized context or error
  Suspense-->>Application: render initialized content
  ErrorBoundary-->>Application: render initialization error
Loading
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: adding the useAuth0Suspense hook for React 19+ authentication loading handling.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch auth0-suspense

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/use-auth0-suspense.tsx`:
- Around line 10-13: Update Auth0SuspenseContextInterface and the
useAuth0Suspense return destructuring to omit _initPromise alongside isLoading
and error, ensuring the internal field is excluded from both the public type and
runtime result.
- Line 1: Update the import in use-auth0-suspense.tsx to use a React namespace
import, and change the hook’s use invocation to React.use while preserving
useContext and the existing behavior. This avoids requiring a static named use
export from older supported React versions.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 1c9f4d54-bc0f-4e6e-8254-1c70f6a0094b

📥 Commits

Reviewing files that changed from the base of the PR and between 361c018 and 7eeb79a.

📒 Files selected for processing (7)
  • EXAMPLES.md
  • __tests__/auth-provider.test.tsx
  • __tests__/use-auth0-suspense.test.tsx
  • src/auth0-context.tsx
  • src/auth0-provider.tsx
  • src/index.tsx
  • src/use-auth0-suspense.tsx

Comment thread src/use-auth0-suspense.tsx Outdated
Comment thread src/use-auth0-suspense.tsx
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant