> For the complete documentation index, see [llms.txt](https://docs.humanity.org/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.humanity.org/build-with-humanity/build-with-the-sdk-api/humanity-org-react-sdk/hooks.md).

# Hooks

All hooks must be called inside a component that is a descendant of [`HumanityProvider`](/build-with-humanity/build-with-the-sdk-api/humanity-org-react-sdk/components.md#humanityprovider). Calling them outside will throw an error.

***

## TypeScript Types

All types are exported directly from `@humanity-org/react-sdk`:

```typescript
// Auth
type AuthStatus = 'loading' | 'authenticated' | 'unauthenticated';
type Environment = 'production' | 'sandbox';
type StorageStrategy = 'memory' | 'localStorage' | 'sessionStorage';
type OAuthMode = 'popup' | 'redirect';

// User profile (returned after login)
interface UserProfile {
  sub: string;             // Unique user ID
  email?: string;
  name?: string;
  humanity_score?: number;
  // Additional fields depending on granted scopes
}

// Auth operation result
interface AuthResult {
  user: UserProfile;
  accessToken: string;
}

// Verification result
interface VerificationResult {
  preset: string;
  verified: boolean;
  status: 'valid' | 'expired' | 'pending' | 'unavailable';
  expiresAt?: string;
}

type PresetStatus = 'valid' | 'expired' | 'pending' | 'unavailable';
```

## `useHumanity()`

Full-access hook to the entire SDK context. Includes both auth state and verification operations.

```tsx
import { useHumanity } from '@humanity-org/react-sdk';

function MyComponent() {
  const {
    user,
    accessToken,
    authStatus,
    isAuthenticated,
    isLoading,
    error,
    login,
    logout,
    refreshToken,
    verify,
    verifyMultiple,
  } = useHumanity();
}
```

> ℹ️ **Note:** For most use cases, prefer the focused hooks below (`useAuth`, `useVerification`) — they select only what they need and avoid unnecessary re-renders.

***

**Returns**

| Field             | Type                                                    | Description                                              |
| ----------------- | ------------------------------------------------------- | -------------------------------------------------------- |
| `user`            | HumanityUser                                            | null                                                     |
| `accessToken`     | string                                                  | null                                                     |
| `authStatus`      | 'idle'                                                  | 'loading'                                                |
| `isAuthenticated` | boolean                                                 | true when the user is authenticated.                     |
| `isLoading`       | boolean                                                 | true while an auth or verification request is in-flight. |
| `error`           | HumanityReactError                                      | null                                                     |
| `login`           | () => Promise                                           | Initiate the login flow.                                 |
| `logout`          | () => void                                              | Log out and clear the session.                           |
| `refreshToken`    | () => Promise                                           | Manually refresh the access token.                       |
| `verify`          | (preset: string) => Promise                             | Verify a single preset.                                  |
| `verifyMultiple`  | (presets: string\[]) => Promise\<VerificationResult\[]> | Verify multiple presets at once.                         |

## `useAuth()`

Auth-focused hook. Selects only authentication state and operations from the context.

```tsx
import { useAuth } from '@humanity-org/react-sdk';

function LoginButton() {
  const { isAuthenticated, login, logout, isLoading } = useAuth();

  if (isLoading) return <Spinner />;
  if (isAuthenticated) return <button onClick={logout}>Sign Out</button>;
  return <button onClick={() => login()}>Sign In</button>;
}
```

**Returns**

| Field             | Type                                       | Description                              |
| ----------------- | ------------------------------------------ | ---------------------------------------- |
| `isAuthenticated` | boolean                                    | true when the user is authenticated.     |
| `isLoading`       | boolean                                    | true while an auth request is in-flight. |
| `login`           | ({ scopes: \['your\_scopes'] }) => Promise | Initiate the login flow.                 |
| `logout`          | () => void                                 | Log out and clear the session.           |

## `useVerification()`

Runs preset verifications against the Humanity Protocol API. Returns a **discriminated union** `status` for type-safe state narrowing.

```tsx
import { useVerification } from '@humanity-org/react-sdk';

function AgeCheck() {
  const { verify, status, result, isLoading } = useVerification();

  return (
    <div>
      <button onClick={() => verify('ageOver21')} disabled={isLoading}>
        Check Age
      </button>
      {status === 'success' && (
        <p>{result.verified ? '✅ Verified' : '❌ Not verified'}</p>
      )}
      {status === 'error' && <p>Verification failed</p>}
    </div>
  );
}
```

**Returns**

{% hint style="info" %}
`verifyMultiple()` accept a maximum of 10 presets per call.
{% endhint %}

<table><thead><tr><th width="130.70703125">Field</th><th width="423.57421875">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>status</code></td><td><code>'idle' | 'loading' | 'success' | 'error'</code></td><td>Discriminated union status. Narrow with <code>switch</code> or <code>if</code>.</td></tr><tr><td><code>result</code></td><td><code>VerificationResult | null</code></td><td>Verification result when <code>status === 'success'</code>; null otherwise.</td></tr><tr><td><code>error</code></td><td><code>HumanityReactError | null</code></td><td>Error when <code>status === 'error'</code>; null otherwise.</td></tr><tr><td><code>isLoading</code></td><td><code>boolean</code></td><td><code>true</code> while a request is in-flight.</td></tr><tr><td><code>verify</code></td><td><code>(preset: string) => Promise&#x3C;VerificationResult></code></td><td>Verify a single preset.</td></tr><tr><td><code>verifyMultiple</code></td><td><code>(presets: string[]) => Promise&#x3C;VerificationResult[]></code></td><td>Verify multiple presets at once.</td></tr><tr><td><code>reset</code></td><td><code>() => void</code></td><td>Reset to <code>idle</code> state.</td></tr></tbody></table>

{% hint style="info" %}
Use `result.value` to access the actual value for a particular credential.
{% endhint %}

***

## `usePresets()`

Manages and caches multiple preset verifications. Stores results in an internal map for easy per-preset access. Ideal for dashboards that need to check several presets at once.

```tsx
import { usePresets } from '@humanity-org/react-sdk';
import { useEffect } from 'react';

function Dashboard() {
  const { verifyAll, isVerified, getResult, isLoading } = usePresets();

  useEffect(() => {
    verifyAll(['ageOver18', 'kycPassed']);
  }, [verifyAll]);

  if (isLoading) return <Spinner />;

  return (
    <div>
      <p>Age 18+: {isVerified('ageOver18') ? '✅' : '❌'}</p>
      <p>KYC: {isVerified('kycPassed') ? '✅' : '❌'}</p>
    </div>
  );
}
```

{% hint style="info" %}
`verifyAll()` accept a maximum of 10 presets per call.
{% endhint %}

**Returns**

<table><thead><tr><th width="148.3828125">Field</th><th width="373.78515625">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>status</code></td><td><code>'idle' | 'loading' | 'success' | 'error'</code></td><td>Discriminated union status.</td></tr><tr><td><code>results</code></td><td><code>Map&#x3C;string, VerificationResult></code></td><td>Map of preset key → verification result.</td></tr><tr><td><code>error</code></td><td><code>HumanityReactError | null</code></td><td>Error when <code>status === 'error'</code>; null otherwise.</td></tr><tr><td><code>isLoading</code></td><td><code>boolean</code></td><td><code>true</code> while a verification batch is in-flight.</td></tr><tr><td><code>verifyAll</code></td><td><code>(presets: string[]) => Promise&#x3C;VerificationResult[]></code></td><td>Verify a batch of presets; stores all results internally.</td></tr><tr><td><code>getResult</code></td><td><code>(preset: string) => VerificationResult | undefined</code></td><td>Get the cached result for a specific preset.</td></tr><tr><td><code>isVerified</code></td><td><code>(preset: string) => boolean</code></td><td>Quick check: is the given preset verified?</td></tr><tr><td><code>reset</code></td><td><code>() => void</code></td><td>Clear all stored results and reset to <code>idle</code>.</td></tr></tbody></table>

***

## `useCredentialUpdates()`

Polls the Humanity Protocol API for credential updates. Useful for keeping verification status in sync without requiring a full page reload.

```tsx
import { useCredentialUpdates } from '@humanity-org/react-sdk';

function CredentialDashboard() {
  const { data, isLoading, error, refetch } = useCredentialUpdates({
    pollInterval: 30_000, // poll every 30 seconds
    enabled: true,
  });

  if (isLoading && !data) return <Spinner />;
  if (error) return <p>Failed to load credentials</p>;

  return (
    <div>
      <p>Active credentials: {data?.credentials.length ?? 0}</p>
      <button onClick={refetch}>Refresh Now</button>
    </div>
  );
}
```

**Options**

| Option         | Type      | Default | Description                                             |
| -------------- | --------- | ------- | ------------------------------------------------------- |
| `pollInterval` | `number`  | `0`     | Polling interval in milliseconds. `0` disables polling. |
| `enabled`      | `boolean` | `true`  | Whether polling is active.                              |

**Returns**

| Field       | Type                         | Description                          |
| ----------- | ---------------------------- | ------------------------------------ |
| `data`      | `CredentialUpdates \| null`  | Latest credential updates, or null.  |
| `isLoading` | `boolean`                    | `true` while a request is in-flight. |
| `error`     | `HumanityReactError \| null` | Most recent error, or null.          |
| `refetch`   | `() => Promise<void>`        | Manually trigger a fetch.            |

***

## Utilities

## `clearVerificationCache()`

Clears all cached verification results, across every preset, not just the one you most recently checked.

Call it when:

* The user just completed a verification step and you need the new state reflected immediately.
* You've run the user through a re-verification flow and the cached result no longer matches reality.
* You're testing and want a clean slate without reloading the page

```typescript
import { clearVerificationCache } from '@humanity-org/react-sdk';

clearVerificationCache();
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.humanity.org/build-with-humanity/build-with-the-sdk-api/humanity-org-react-sdk/hooks.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
