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

# Getting Started with React SDK

> Install and configure the ZKScore React SDK for your React application

## Overview

The ZKScore React SDK provides React hooks and components for building Web3 applications with ZKScore integration. It includes hooks for scores, identities, achievements, and pre-built components for common use cases.

<Tip>
  The React SDK automatically handles ZKS ID resolution, so you can use either ZKS IDs (like `alice.zks`) or wallet addresses in your components. The SDK will resolve them to the appropriate format.
</Tip>

## Installation

Install the ZKScore React SDK using npm or yarn:

<CodeGroup>
  ```bash npm theme={null}
  npm install @zkscore/sdk-react
  ```

  ```bash yarn theme={null}
  yarn add @zkscore/sdk-react
  ```

  ```bash pnpm theme={null}
  pnpm add @zkscore/sdk-react
  ```
</CodeGroup>

## Quick Start

### 1. Provider Setup

```jsx theme={null}
import React from 'react';
import { ZKScoreProvider } from '@zkscore/sdk-react';

function App() {
  return (
    <ZKScoreProvider
      apiKey="your-api-key-here"
      environment="mainnet"
      config={{
        cache: true,
        realTime: true
      }}
    >
      <YourApp />
    </ZKScoreProvider>
  );
}

export default App;
```

### 2. Environment Configuration

```jsx theme={null}
// Production configuration
import { ZKScoreProvider } from '@zkscore/sdk-react';

function App() {
  return (
    <ZKScoreProvider
      apiKey={process.env.REACT_APP_ZKSCORE_API_KEY}
      environment="mainnet"
      baseUrl="https://api.onzks.com"
      config={{
        cache: {
          enabled: true,
          ttl: 300000, // 5 minutes
          maxSize: 1000
        },
        realTime: {
          enabled: true,
          reconnectInterval: 5000
        },
        retry: {
          attempts: 3,
          delay: 1000
        }
      }}
    >
      <YourApp />
    </ZKScoreProvider>
  );
}
```

### 3. First Hook Usage

```jsx theme={null}
import React from 'react';
import { useScore, useIdentity } from '@zkscore/sdk-react';

function UserProfile({ identity }) {
  const { data: score, loading, error } = useScore(identity);
  const { data: identityData } = useIdentity(identity);

  if (loading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return (
    <div>
      <h2>{identityData?.name || identity}</h2>
      <p>Score: {score?.total || 0}</p>
      <p>Address: {identityData?.address}</p>
    </div>
  );
}

// Usage
function App() {
  return (
    <ZKScoreProvider apiKey="your-api-key">
      <UserProfile identity="alice.zks" />
    </ZKScoreProvider>
  );
}
```

## Configuration Options

### Provider Configuration

<ParamField name="apiKey" type="string" required>
  Your ZKScore API key
</ParamField>

<ParamField name="environment" type="string">
  Environment to use

  * `mainnet` - Production environment (default)
  * `testnet` - Test environment
</ParamField>

<ParamField name="baseUrl" type="string">
  Custom API base URL (optional)
</ParamField>

<ParamField name="config" type="object">
  SDK configuration

  <Expandable title="config properties">
    <ParamField name="cache" type="object">
      Caching configuration

      <Expandable title="cache properties">
        <ParamField name="enabled" type="boolean">
          Enable caching (default: true)
        </ParamField>

        <ParamField name="ttl" type="number">
          Cache time-to-live in milliseconds (default: 300000)
        </ParamField>

        <ParamField name="maxSize" type="number">
          Maximum cache size (default: 1000)
        </ParamField>
      </Expandable>
    </ParamField>

    <ParamField name="realTime" type="object">
      Real-time updates configuration

      <Expandable title="realTime properties">
        <ParamField name="enabled" type="boolean">
          Enable real-time updates (default: true)
        </ParamField>

        <ParamField name="reconnectInterval" type="number">
          Reconnection interval in milliseconds (default: 5000)
        </ParamField>
      </Expandable>
    </ParamField>

    <ParamField name="retry" type="object">
      Retry configuration

      <Expandable title="retry properties">
        <ParamField name="attempts" type="number">
          Number of retry attempts (default: 3)
        </ParamField>

        <ParamField name="delay" type="number">
          Delay between retries in milliseconds (default: 1000)
        </ParamField>
      </Expandable>
    </ParamField>
  </Expandable>
</ParamField>

## Core Hooks

### 1. useScore Hook

```jsx theme={null}
import { useScore } from '@zkscore/sdk-react';

function ScoreDisplay({ identity }) {
  const { 
    data: score, 
    loading, 
    error, 
    refetch 
  } = useScore(identity, {
    chainId: 1,
    includeBreakdown: true,
    realTime: true
  });

  if (loading) return <div>Loading score...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return (
    <div>
      <h3>Score: {score?.total || 0}</h3>
      {score?.breakdown && (
        <div>
          <p>DeFi: {score.breakdown.defi}</p>
          <p>NFT: {score.breakdown.nft}</p>
          <p>Social: {score.breakdown.social}</p>
        </div>
      )}
      <button onClick={() => refetch()}>Refresh</button>
    </div>
  );
}
```

### 2. useIdentity Hook

```jsx theme={null}
import { useIdentity } from '@zkscore/sdk-react';

function IdentityCard({ identity }) {
  const { 
    data: identityData, 
    loading, 
    error 
  } = useIdentity(identity, {
    chainId: 1
  });

  if (loading) return <div>Loading identity...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return (
    <div className="identity-card">
      <h3>{identityData?.name || identity}</h3>
      <p>Address: {identityData?.address}</p>
      <p>Token ID: {identityData?.tokenId}</p>
      <p>Activated: {identityData?.isActivated ? 'Yes' : 'No'}</p>
      {identityData?.metadata && (
        <div>
          <p>Bio: {identityData.metadata.bio}</p>
          <img src={identityData.metadata.avatar} alt="Avatar" />
        </div>
      )}
    </div>
  );
}
```

### 3. useAchievements Hook

```jsx theme={null}
import { useAchievements } from '@zkscore/sdk-react';

function AchievementsList({ identity }) {
  const { 
    data: achievements, 
    loading, 
    error 
  } = useAchievements(identity, {
    category: 'defi',
    status: 'earned',
    limit: 10
  });

  if (loading) return <div>Loading achievements...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return (
    <div>
      <h3>Achievements ({achievements?.earned?.length || 0})</h3>
      {achievements?.earned?.map(achievement => (
        <div key={achievement.id} className="achievement">
          <h4>{achievement.name}</h4>
          <p>{achievement.description}</p>
          <p>Points: {achievement.points}</p>
          <p>Rarity: {achievement.rarity}</p>
        </div>
      ))}
    </div>
  );
}
```

### 4. useScoreHistory Hook

```jsx theme={null}
import { useScoreHistory } from '@zkscore/sdk-react';

function ScoreChart({ identity }) {
  const { 
    data: history, 
    loading, 
    error 
  } = useScoreHistory(identity, {
    timeframe: '30d',
    interval: 'daily',
    chainId: 1
  });

  if (loading) return <div>Loading score history...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return (
    <div>
      <h3>Score History (30 days)</h3>
      <div className="chart">
        {history?.map((point, index) => (
          <div 
            key={index} 
            className="chart-bar"
            style={{ height: `${(point.total / 1000) * 100}%` }}
            title={`${point.total} on ${point.timestamp}`}
          />
        ))}
      </div>
    </div>
  );
}
```

### 5. useTrustScore Hook

```jsx theme={null}
import { useTrustScore } from '@zkscore/sdk-react';

function TrustScoreDisplay({ identity }) {
  const { 
    data: trustScore, 
    loading, 
    error 
  } = useTrustScore(identity, {
    realTime: true
  });

  if (loading) return <div>Loading trust score...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return (
    <div>
      <h3>Trust Score: {trustScore?.total || 0}</h3>
      <p>Attestations: {trustScore?.attestations || 0}</p>
      <p>Verifiers: {trustScore?.verifiers || 0}</p>
    </div>
  );
}
```

## TypeScript Support

### 1. Type Definitions

```typescript theme={null}
import { 
  useScore, 
  useIdentity, 
  useAchievements,
  ScoreData,
  Identity,
  Achievement
} from '@zkscore/sdk-react';

interface UserProfileProps {
  identity: string;
}

function UserProfile({ identity }: UserProfileProps) {
  const { data: score } = useScore(identity);
  const { data: identityData } = useIdentity(identity);
  const { data: achievements } = useAchievements(identity);

  return (
    <div>
      <h2>{identityData?.name || identity}</h2>
      <p>Score: {score?.total || 0}</p>
      <p>Achievements: {achievements?.earned?.length || 0}</p>
    </div>
  );
}
```

### 2. Custom Hook Types

```typescript theme={null}
interface UseScoreOptions {
  chainId?: number;
  includeBreakdown?: boolean;
  realTime?: boolean;
  enabled?: boolean;
}

interface UseScoreReturn {
  data: ScoreData | undefined;
  loading: boolean;
  error: Error | null;
  refetch: () => void;
}

function useScore(identity: string, options?: UseScoreOptions): UseScoreReturn {
  // Implementation
}
```

## Error Handling

### 1. Global Error Boundary

```jsx theme={null}
import React from 'react';
import { ZKScoreProvider } from '@zkscore/sdk-react';

class ZKScoreErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false, error: null };
  }

  static getDerivedStateFromError(error) {
    return { hasError: true, error };
  }

  componentDidCatch(error, errorInfo) {
    console.error('ZKScore Error:', error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return (
        <div className="error-boundary">
          <h2>Something went wrong with ZKScore</h2>
          <p>{this.state.error?.message}</p>
          <button onClick={() => this.setState({ hasError: false, error: null })}>
            Try Again
          </button>
        </div>
      );
    }

    return this.props.children;
  }
}

function App() {
  return (
    <ZKScoreErrorBoundary>
      <ZKScoreProvider apiKey="your-api-key">
        <YourApp />
      </ZKScoreProvider>
    </ZKScoreErrorBoundary>
  );
}
```

### 2. Hook-Level Error Handling

```jsx theme={null}
import { useScore } from '@zkscore/sdk-react';

function ScoreDisplay({ identity }) {
  const { data: score, loading, error, refetch } = useScore(identity);

  if (loading) return <div>Loading...</div>;
  
  if (error) {
    return (
      <div className="error">
        <p>Error loading score: {error.message}</p>
        <button onClick={() => refetch()}>Retry</button>
      </div>
    );
  }

  return <div>Score: {score?.total || 0}</div>;
}
```

## Caching and Performance

### 1. Cache Configuration

```jsx theme={null}
import { ZKScoreProvider } from '@zkscore/sdk-react';

function App() {
  return (
    <ZKScoreProvider
      apiKey="your-api-key"
      config={{
        cache: {
          enabled: true,
          ttl: 300000, // 5 minutes
          maxSize: 1000,
          storage: 'memory' // or 'localStorage'
        }
      }}
    >
      <YourApp />
    </ZKScoreProvider>
  );
}
```

### 2. Cache Management

```jsx theme={null}
import { useZKScoreContext } from '@zkscore/sdk-react';

function CacheManager() {
  const { cache } = useZKScoreContext();

  const clearCache = () => {
    cache.clear();
  };

  const getCacheStats = () => {
    return cache.getStats();
  };

  return (
    <div>
      <button onClick={clearCache}>Clear Cache</button>
      <p>Cache Stats: {JSON.stringify(getCacheStats())}</p>
    </div>
  );
}
```

## Real-time Updates

### 1. Real-time Configuration

```jsx theme={null}
import { ZKScoreProvider } from '@zkscore/sdk-react';

function App() {
  return (
    <ZKScoreProvider
      apiKey="your-api-key"
      config={{
        realTime: {
          enabled: true,
          reconnectInterval: 5000,
          maxReconnectAttempts: 5
        }
      }}
    >
      <YourApp />
    </ZKScoreProvider>
  );
}
```

### 2. Real-time Hook Usage

```jsx theme={null}
import { useScore } from '@zkscore/sdk-react';

function RealTimeScore({ identity }) {
  const { data: score, loading } = useScore(identity, {
    realTime: true
  });

  return (
    <div>
      <h3>Real-time Score: {score?.total || 0}</h3>
      {loading && <p>Updating...</p>}
    </div>
  );
}
```

## Best Practices

### 1. Environment Variables

```jsx theme={null}
// .env file
REACT_APP_ZKSCORE_API_KEY=your-api-key-here
REACT_APP_ZKSCORE_ENVIRONMENT=mainnet
REACT_APP_ZKSCORE_CACHE_TTL=300000

// Configuration
import { ZKScoreProvider } from '@zkscore/sdk-react';

function App() {
  return (
    <ZKScoreProvider
      apiKey={process.env.REACT_APP_ZKSCORE_API_KEY}
      environment={process.env.REACT_APP_ZKSCORE_ENVIRONMENT || 'mainnet'}
      config={{
        cache: {
          ttl: parseInt(process.env.REACT_APP_ZKSCORE_CACHE_TTL) || 300000
        }
      }}
    >
      <YourApp />
    </ZKScoreProvider>
  );
}
```

### 2. Conditional Rendering

```jsx theme={null}
import { useScore, useIdentity } from '@zkscore/sdk-react';

function ConditionalProfile({ identity, showScore = true }) {
  const { data: identityData, loading: identityLoading } = useIdentity(identity);
  const { data: score, loading: scoreLoading } = useScore(identity, {
    enabled: showScore
  });

  if (identityLoading) return <div>Loading identity...</div>;

  return (
    <div>
      <h2>{identityData?.name || identity}</h2>
      {showScore && (
        <div>
          {scoreLoading ? (
            <p>Loading score...</p>
          ) : (
            <p>Score: {score?.total || 0}</p>
          )}
        </div>
      )}
    </div>
  );
}
```

### 3. Error Recovery

```jsx theme={null}
import { useScore } from '@zkscore/sdk-react';

function ResilientScoreDisplay({ identity }) {
  const { data: score, loading, error, refetch } = useScore(identity);

  const handleRetry = () => {
    refetch();
  };

  if (loading) return <div>Loading...</div>;

  if (error) {
    return (
      <div className="error-container">
        <p>Failed to load score: {error.message}</p>
        <button onClick={handleRetry}>Retry</button>
      </div>
    );
  }

  return <div>Score: {score?.total || 0}</div>;
}
```

## Troubleshooting

### Common Issues

**1. "Provider not found" Error**

```jsx theme={null}
// Make sure ZKScoreProvider wraps your app
function App() {
  return (
    <ZKScoreProvider apiKey="your-api-key">
      <YourComponents />
    </ZKScoreProvider>
  );
}
```

**2. "Invalid API Key" Error**

```jsx theme={null}
// Check your API key
console.log('API Key:', process.env.REACT_APP_ZKSCORE_API_KEY);

// Verify key format
const isValidKey = /^zk_[a-zA-Z0-9]{40}$/.test(process.env.REACT_APP_ZKSCORE_API_KEY);
console.log('Valid format:', isValidKey);
```

**3. "Network Error" Issues**

```jsx theme={null}
// Check network connectivity
import { useZKScoreContext } from '@zkscore/sdk-react';

function NetworkStatus() {
  const { isConnected, connectionError } = useZKScoreContext();

  if (!isConnected) {
    return (
      <div className="network-error">
        <p>Network connection failed: {connectionError}</p>
        <button onClick={() => window.location.reload()}>Retry</button>
      </div>
    );
  }

  return <div>Connected to ZKScore</div>;
}
```

## Related Documentation

* [Hooks Reference](/sdk/react/hooks-reference) - Complete hooks API
* [Components](/sdk/react/components) - Pre-built components
* [Examples](/sdk/react/examples) - Complete examples
* [JavaScript SDK](/sdk/javascript/getting-started) - Core SDK documentation

## Support

For additional help:

* **Documentation**: [docs.onzks.com](https://docs.onzks.com)
* **GitHub**: [github.com/zkscore/sdk-react](https://github.com/zkscore/sdk-react)
* **Discord**: [discord.gg/zkscore](https://discord.gg/zkscore)
* **Email**: [support@onzks.com](mailto:support@onzks.com)
