# React Integration

Add **analytics to your React Figma plugin** with the `useTode` hook. This guide covers everything you need to track user actions in your React-based Figma plugins and widgets.

Starting from zero? `npm create @tode-sdk@latest my-plugin -- --framework react` gives you all of this already in place; see [Start from a template](https://docs.usetode.dev/template).

## Installation

Install the core SDK and React adapter:

```bash
npm install @tode-sdk/core @tode-sdk/figma-react
```

## Setup

### Initialize in Plugin Controller

First, set up Tode in your plugin's main code file:

`code.ts`:

```typescript
import { tode } from '@tode-sdk/core';

// Show your React UI
figma.showUI(__html__, { width: 400, height: 600 });

// Initialize Tode for Figma plugin analytics
await tode.init({ apiKey: 'your-api-key' });

// Optional: Track plugin open from controller
tode.trackAction('plugin_opened');
```

### Configure Network Access

Add Tode's URLs to your plugin's `manifest.json` to enable analytics requests, and the `currentuser` permission so the SDK can read `figma.currentUser.id`. Without that permission events still arrive, but they are anonymous and the dashboard cannot count unique users. [Learn more about network access](https://developers.figma.com/docs/plugins/making-network-requests/).

```json title="manifest.json"
{
  "name": "Your Plugin",
  "id": "your-plugin-id",
  "api": "1.0.0",
  "main": "code.js",
  "ui": "index.html",
  "permissions": ["currentuser"],
  "networkAccess": {
    "allowedDomains": [
      "https://processing.usetode.dev",
      "wss://processing.usetode.dev"
    ]
  }
}
```

### Use the Hook in Your React UI

Use the `useTode` hook in your React components:

`App.tsx`:

```tsx
import { useTode } from '@tode-sdk/figma-react';

function App() {
  const { tode, isReady } = useTode();

  const handleExport = () => {
    if (isReady) {
      tode.trackAction('export_clicked');
    }
  };

  return (
    <button onClick={handleExport} disabled={!isReady}>
      Export Design
    </button>
  );
}
```

## Hook Reference

### useTode()

Returns an object with:

| Property | Type | Description |
|----------|------|-------------|
| `tode` | `Tode` | The Tode instance for tracking |
| `isReady` | `boolean` | Whether Tode is initialized and ready ([`tode.isReady`](https://docs.usetode.dev/api#todeisready)) |
| `wsState` | `WebSocketState` | Session connection state: `disconnected`, `connecting`, `connected` or `error` |
| `trackAction(name, options?)` | `function` | Same as `tode.trackAction`; the function identity is stable across renders |
| `trackActionWithMetric(name, value, options?)` | `function` | Same as `tode.trackActionWithMetric`; stable across renders |

`useTode()` takes an optional object:

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `debug` | `boolean` | `false` | Log adapter activity to the console |
| `pingInterval` | `number` | `5000` | Keepalive ping interval in ms |
| `onWebSocketStateChange` | `(state) => void` | - | Called on every `wsState` change |

The session connection is shared: however many components use Tode, the plugin UI opens one WebSocket and counts as one session. It closes when the last of them is gone.

## Examples

### Track Button Clicks

`ToolButton.tsx`:

```tsx
import { useTode } from '@tode-sdk/figma-react';

function ToolButton({ tool }: { tool: string }) {
  const { tode, isReady } = useTode();

  const handleClick = () => {
    if (isReady) {
      tode.trackAction(`tool_selected_${tool}`);
    }
  };

  return <button onClick={handleClick}>{tool}</button>;
}
```

### Track with Metrics

`ExportPanel.tsx`:

```tsx
import { useTode } from '@tode-sdk/figma-react';

function ExportPanel() {
  const { tode, isReady } = useTode();

  const handleExport = async (items: any[]) => {
    // Perform export logic...

    // Track export with item count
    if (isReady) {
      tode.trackActionWithMetric('items_exported', items.length);
    }
  };

  return (
    <button onClick={() => handleExport(selectedItems)}>
      Export Selected
    </button>
  );
}
```

### Track Feature View Once

`FeatureComponent.tsx`:

```tsx
import { useTode } from '@tode-sdk/figma-react';
import { useState, useEffect } from 'react';

function FeatureComponent() {
  const { tode, isReady } = useTode();
  const [hasTrackedView, setHasTrackedView] = useState(false);

  useEffect(() => {
    if (isReady && !hasTrackedView) {
      tode.trackAction('feature_viewed');
      setHasTrackedView(true);
    }
  }, [isReady, hasTrackedView]);

  return <div>Feature Content</div>;
}
```

## Best Practices

### 1. Track Without Waiting for `isReady`

Events tracked before Tode is ready are held and sent once it is, so the check is optional:

```tsx
// Works on the first render too
tode.trackAction('action');

// isReady is for UI state
<button disabled={!isReady}>Export</button>
```

### 2. Use Descriptive Action Names

Choose clear, consistent names for your Figma plugin analytics:

```tsx
// Good
tode.trackAction('export_to_png');
tode.trackAction('layer_renamed');
tode.trackAction('settings_opened');

// Bad - too vague
tode.trackAction('click');
tode.trackAction('action1');
```

### 3. Track Key User Journeys

Focus on tracking actions that matter:

- Plugin open
- Core feature usage
- Export/save actions
- Settings changes

## Next Steps

- Learn about the [API Reference](https://docs.usetode.dev/api) for all available methods
- See other framework guides: [Vue](https://docs.usetode.dev/vue), [Angular](https://docs.usetode.dev/angular), [Svelte](https://docs.usetode.dev/svelte)

Source: https://docs.usetode.dev/react
