# Hooks

All hooks must be called inside a component that is a descendant of [`HumanityProvider`](https://docs.humanity.org/build-with-humanity/build-with-the-sdk-api/components#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                              |
| ----------------- | ------------- | ---------------------------------------- |
| i`sAuthenticated` | boolean       | true when the user is authenticated.     |
| `isLoading`       | boolean       | true while an auth request is in-flight. |
| `login`           | () => 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**

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

***

## `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>
  );
}
```

**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.            |

***
