> ## Documentation Index
> Fetch the complete documentation index at: https://docs.usmewe.com/llms.txt
> Use this file to discover all available pages before exploring further.

# React Hooks

> React hooks for usmewe integration

# React Hooks

React-specific hooks for seamless usmewe integration.

## Installation

<CodeGroup>
  ```bash npm theme={null}
  npm install @usmewe/react
  ```

  ```bash yarn theme={null}
  yarn add @usmewe/react
  ```

  ```bash pnpm theme={null}
  pnpm add @usmewe/react
  ```
</CodeGroup>

## Setup

Wrap your app with the `UsmeweProvider`:

```tsx theme={null}
import { UsmeweProvider } from '@usmewe/react';

function App() {
  return (
    <UsmeweProvider
      config={{
        environment: 'production',
        // apiKey or token can be set here or later
      }}
    >
      <YourApp />
    </UsmeweProvider>
  );
}
```

## Authentication

### useUsmeweAuth

Manage authentication state:

```tsx theme={null}
import { useUsmeweAuth } from '@usmewe/react';

function LoginButton() {
  const { isAuthenticated, login, logout, user } = useUsmeweAuth();

  if (isAuthenticated) {
    return (
      <div>
        <p>Welcome, {user.displayName}</p>
        <button onClick={logout}>Logout</button>
      </div>
    );
  }

  return <button onClick={() => login(token)}>Login</button>;
}
```

## User Hooks

### useUser

Get current user data:

```tsx theme={null}
import { useUser } from '@usmewe/react';

function Profile() {
  const { user, isLoading, error, refetch } = useUser();

  if (isLoading) return <Spinner />;
  if (error) return <Error message={error.message} />;

  return (
    <div>
      <h1>{user.displayName}</h1>
      <p>Trust Score: {user.trustScore}</p>
      <p>Level: {user.level}</p>
    </div>
  );
}
```

### useTrustScore

Get Trust Score with breakdown:

```tsx theme={null}
import { useTrustScore } from '@usmewe/react';

function TrustScoreCard() {
  const { score, breakdown, tier, isLoading } = useTrustScore();

  if (isLoading) return <Skeleton />;

  return (
    <div>
      <h2>Trust Score: {score}</h2>
      <p>Tier: {tier}</p>

      <div className="breakdown">
        <p>Seniority: {breakdown.seniority}/12</p>
        <p>Repayments: {breakdown.repaymentHistory}/40</p>
        <p>Volume: {breakdown.transactionVolume}/20</p>
        <p>Social: {breakdown.socialNetwork}/15</p>
        <p>Level: {breakdown.levelBonus}/13</p>
      </div>
    </div>
  );
}
```

## Loan Hooks

### useLoanEligibility

Check loan eligibility:

```tsx theme={null}
import { useLoanEligibility } from '@usmewe/react';

function LoanForm() {
  const { eligible, maxAmount, maxDuration, restrictions } = useLoanEligibility();

  if (!eligible) {
    return (
      <Alert>
        You're not eligible: {restrictions.join(', ')}
      </Alert>
    );
  }

  return (
    <form>
      <p>Max amount: ${maxAmount}</p>
      <p>Max duration: {maxDuration} days</p>
      {/* Form fields */}
    </form>
  );
}
```

### useLoans

List and manage loans:

```tsx theme={null}
import { useLoans } from '@usmewe/react';

function LoanList() {
  const {
    loans,
    isLoading,
    createLoan,
    repayLoan,
    isCreating,
    isRepaying
  } = useLoans({ status: 'active' });

  const handleCreate = async () => {
    await createLoan({
      amount: 50,
      duration: 14
    });
  };

  const handleRepay = async (loanId: string, amount: number) => {
    await repayLoan(loanId, amount);
  };

  return (
    <div>
      <button onClick={handleCreate} disabled={isCreating}>
        {isCreating ? 'Creating...' : 'New Loan'}
      </button>

      {loans.map(loan => (
        <LoanCard
          key={loan.id}
          loan={loan}
          onRepay={() => handleRepay(loan.id, loan.remainingBalance)}
        />
      ))}
    </div>
  );
}
```

### useLoan

Get single loan details:

```tsx theme={null}
import { useLoan } from '@usmewe/react';

function LoanDetails({ loanId }: { loanId: string }) {
  const { loan, isLoading, repay, cancel } = useLoan(loanId);

  if (isLoading) return <Spinner />;

  return (
    <div>
      <h2>Loan #{loan.id}</h2>
      <p>Amount: ${loan.amount}</p>
      <p>Status: {loan.status}</p>
      <p>Due: {loan.dueDate}</p>

      {loan.status === 'active' && (
        <button onClick={() => repay(loan.totalRepayment)}>
          Repay ${loan.totalRepayment}
        </button>
      )}

      {loan.status === 'pending' && (
        <button onClick={cancel}>Cancel</button>
      )}
    </div>
  );
}
```

## Vault Hooks

### useVault

Manage Trust Vault position:

```tsx theme={null}
import { useVault } from '@usmewe/react';

function VaultDashboard() {
  const {
    position,
    vaultStatus,
    deposit,
    withdraw,
    isDepositing,
    isWithdrawing
  } = useVault();

  return (
    <div>
      <h2>Your Position</h2>
      <p>tmUSDC: {position.tmUSDCBalance}</p>
      <p>Value: ${position.usdcValue}</p>
      <p>Earned: ${position.earnedYield}</p>

      <h3>Vault Stats</h3>
      <p>APY: {(vaultStatus.currentAPY * 100).toFixed(2)}%</p>
      <p>Utilization: {(vaultStatus.utilization * 100).toFixed(0)}%</p>

      <button
        onClick={() => deposit(100)}
        disabled={isDepositing}
      >
        Deposit $100
      </button>

      <button
        onClick={() => withdraw(50)}
        disabled={isWithdrawing}
      >
        Withdraw 50 tmUSDC
      </button>
    </div>
  );
}
```

## Social Vault Hooks

### useSocialVault

Manage Social Vault:

```tsx theme={null}
import { useSocialVault } from '@usmewe/react';

function SocialVaultPanel() {
  const {
    config,
    balance,
    pendingWithdrawals,
    instantWithdraw,
    requestWithdrawal,
    lock
  } = useSocialVault();

  return (
    <div>
      <h2>Social Vault</h2>
      <p>Balance: ${balance}</p>
      <p>Daily Limit: ${config.dailyLimit}</p>

      <button onClick={() => instantWithdraw(50, recipientAddress)}>
        Instant Withdraw $50
      </button>

      <h3>Pending Withdrawals</h3>
      {pendingWithdrawals.map(w => (
        <div key={w.id}>
          <p>${w.amount} - {w.approvalsReceived}/{w.approvalsRequired}</p>
        </div>
      ))}
    </div>
  );
}
```

### useGuardians

Manage guardians:

```tsx theme={null}
import { useGuardians } from '@usmewe/react';

function GuardianList() {
  const {
    guardians,
    addGuardian,
    removeGuardian,
    isAdding
  } = useGuardians();

  return (
    <div>
      <h2>Your Guardians ({guardians.length}/3)</h2>

      {guardians.map(g => (
        <div key={g.id}>
          <p>{g.displayName}</p>
          <button onClick={() => removeGuardian(g.id)}>Remove</button>
        </div>
      ))}

      {guardians.length < 3 && (
        <button
          onClick={() => addGuardian('0x...')}
          disabled={isAdding}
        >
          Add Guardian
        </button>
      )}
    </div>
  );
}
```

## Notification Hooks

### useNotifications

Manage notifications:

```tsx theme={null}
import { useNotifications } from '@usmewe/react';

function NotificationBell() {
  const {
    notifications,
    unreadCount,
    markAsRead,
    markAllAsRead
  } = useNotifications();

  return (
    <div>
      <span className="badge">{unreadCount}</span>

      {notifications.map(n => (
        <div
          key={n.id}
          className={n.read ? 'read' : 'unread'}
          onClick={() => markAsRead(n.id)}
        >
          <h4>{n.title}</h4>
          <p>{n.body}</p>
        </div>
      ))}

      <button onClick={markAllAsRead}>Mark all read</button>
    </div>
  );
}
```

## Optimistic Updates

Hooks support optimistic updates for instant feedback:

```tsx theme={null}
const { repayLoan } = useLoans();

// Shows as repaid immediately, rolls back on error
await repayLoan(loanId, amount, { optimistic: true });
```

## Error Handling

```tsx theme={null}
import { useLoans, UsmeweError } from '@usmewe/react';

function LoanForm() {
  const { createLoan, error } = useLoans();

  useEffect(() => {
    if (error) {
      toast.error(error.message);
    }
  }, [error]);

  // ...
}
```

## TypeScript

All hooks are fully typed:

```tsx theme={null}
import type { Loan, User, TrustScore } from '@usmewe/react';

const MyComponent: React.FC<{ loan: Loan }> = ({ loan }) => {
  // Full type support
};
```

<CardGroup cols={2}>
  <Card title="JavaScript SDK" icon="js" href="/developers/sdks/javascript">
    Core SDK documentation
  </Card>

  <Card title="API Reference" icon="code" href="/developers/api-reference/overview">
    Full API documentation
  </Card>
</CardGroup>
