Skip to content

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

Merged
gyaneshgouraw-okta merged 6 commits into
mainfrom
auth0-suspense
Aug 12, 2026
Merged

feat: add useAuth0Suspense hook for handling auth loading state with React 19+#1184
gyaneshgouraw-okta merged 6 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.

Summary by CodeRabbit

  • New Features

    • Added useAuth0Suspense for React 19+ applications, enabling Auth0 initialization with React Suspense and Error Boundaries.
    • Exported the new hook and its associated type from the package.
    • Added retry handling after initialization or authentication failures.
  • Documentation

    • Added API reference and usage examples for useAuth0Suspense, including setup requirements and error handling.

@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
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: b3649f82-7733-474f-964d-4431898dd71a

📥 Commits

Reviewing files that changed from the base of the PR and between 44b10e2 and c2222d8.

📒 Files selected for processing (6)
  • EXAMPLES.md
  • README.md
  • __tests__/use-auth0-suspense.test.tsx
  • src/auth0-context.tsx
  • src/auth0-provider.tsx
  • src/use-auth0-suspense.tsx
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/auth0-context.tsx
  • EXAMPLES.md

📝 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, README.md
Tests cover initialization, failures, recovery, retry limits, state changes, provider and React version errors, promise stability, and exports. Documentation adds React 19 usage guidance and API references.

Estimated code review effort: 4 (Complex) | ~45 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
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 React 19+ useAuth0Suspense hook for authentication loading state handling.
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.
✨ 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
Contributor

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
Comment thread src/use-auth0-suspense.tsx
Comment thread src/use-auth0-suspense.tsx
Comment thread src/auth0-provider.tsx
Comment thread src/auth0-provider.tsx Outdated
Comment thread src/use-auth0-suspense.tsx Outdated
Comment thread src/index.tsx
Comment thread EXAMPLES.md Outdated

@yogeshchoudhary147 yogeshchoudhary147 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Nice addition! Few things to fix before we merge:

  • Move useContext above the React.use check, hooks ordering issue (cschetan77's comment)
  • Wrap the rest-spread return in useMemo otherwise a new object gets created on every render (subhankarmaiti's comment)
  • The _initPromise rejection is permanent so Error Boundary retries will not work (subhankarmaiti's comment)
  • Provider guard is fragile, please check cschetan77's suggestion on that

Fix these and we are good to go!

@gyaneshgouraw-okta

Copy link
Copy Markdown
Contributor Author

Nice addition! Few things to fix before we merge:

  • Move useContext above the React.use check, hooks ordering issue (cschetan77's comment)
  • Wrap the rest-spread return in useMemo otherwise a new object gets created on every render (subhankarmaiti's comment)
  • The _initPromise rejection is permanent so Error Boundary retries will not work (subhankarmaiti's comment)
  • Provider guard is fragile, please check cschetan77's suggestion on that

Fix these and we are good to go!

Hey @yogeshchoudhary147
Addressed all review, updated changes in this commit. 5f68409

@gyaneshgouraw-okta
gyaneshgouraw-okta merged commit b357ff7 into main Aug 12, 2026
16 checks passed
@gyaneshgouraw-okta
gyaneshgouraw-okta deleted the auth0-suspense branch August 12, 2026 05:41
gyaneshgouraw-okta added a commit that referenced this pull request Aug 12, 2026
**Added**
- feat: add useAuth0Suspense hook for handling auth loading state with
React 19+ [\#1184](#1184)
([gyaneshgouraw-okta](https://github.com/gyaneshgouraw-okta))


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

- **New Features**
- Added API documentation for `useAuth0Suspense` and its suspense
context type, including usage guidance and React 19 requirements.
  - Added the new API to the documentation index and search navigation.

- **Documentation**
- Refreshed generated API references, hierarchy links, source links, and
search data for accuracy.
- Updated documentation metadata across authentication, MFA, passkey,
popup, and configuration APIs.

- **Chores**
  - Bumped the package version to **2.24.0**.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
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.

4 participants