npm package: @gridkit/tanstack-adapter
Description: GridKit Enhanced adapter for TanStack Table - adds enterprise features to TanStack Table
Author: GridKit Team
Latest version: 0.1.1

# @gridkit/tanstack-adapter

> **Enterprise features for TanStack Table** — zero migration, zero performance cost

[![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
[![npm](https://img.shields.io/npm/v/@gridkit/tanstack-adapter)](https://www.npmjs.com/package/@gridkit/tanstack-adapter)

## What Is It?

GridKit Enhanced is a **drop-in wrapper** for TanStack Table that adds enterprise features **without modifying your existing code**.

**How it works:** You create a normal TanStack Table, then wrap it with GridKit to unlock additional capabilities. Your table keeps working exactly as before — you just gain new APIs.

![GridKit Enhanced Architecture](https://habrastorage.org/webt/7j/xv/3y/7jxv3yssdmbdsjypj-t3xugqvcs.png)

## Live Demo

🎯 **[Try GridKit Enhanced on CodeSandbox](https://codesandbox.io/p/sandbox/gridkit-exchanged-chykt4)**

6 interactive examples. 30 seconds to try. No installation needed.

**Features demonstrated:**

- ✅ Event system (no `useEffect` chains)
- ✅ Plugin toggles (Audit Log, Analytics, Export)
- ✅ Performance metrics
- ✅ Interactive data table (100-10,000 rows)

[Open demo in new tab →](https://codesandbox.io/p/sandbox/gridkit-exchanged-chykt4)

---

## Installation

```bash
npm install @gridkit/tanstack-adapter @tanstack/react-table
```

## Quick Start

### Step 1: Create Your TanStack Table (as usual)

```tsx
import { useReactTable, getCoreRowModel } from '@tanstack/react-table';

const tanstackTable = useReactTable({
  columns,
  data,
  getCoreRowModel: getCoreRowModel(),
  // ... your existing config
});
```

### Step 2: Wrap with GridKit (optional)

```tsx
import { createEnhancedTable } from '@gridkit/tanstack-adapter';

const table = createEnhancedTable(tanstackTable, {
  events: true, // Enable event system
  performance: true, // Enable performance monitoring
});
```

### Step 3: Use New Capabilities

```tsx
// Event tracking — no useEffect needed
table.on('row:select', (e) => {
  analytics.track('row_selected', e.payload);
});

// Performance metrics
const stats = table.metrics.getOperationStats('getRowModel');

// Plugins
table.registerPlugin(auditLogPlugin({ destination: '/api/audit' }));
```

**That's it!** Your table still works with all TanStack APIs (`getRowModel()`, `getHeaderGroups()`, etc.), plus you have new tools.

---

## Before vs After

| Task                  | Before (TanStack Only) | After (GridKit)      |
| --------------------- | ---------------------- | -------------------- |
| Track row clicks      | 30+ lines, `useEffect` | 1 line, `table.on()` |
| Audit logging         | 200+ lines custom code | 1 plugin             |
| Performance metrics   | Manual instrumentation | Built-in             |
| Export CSV/Excel      | Build from scratch     | 1 plugin             |
| Schema validation     | Custom validators      | Zod/Yup built-in     |
| **Time to implement** | **3-4 weeks**          | **2-3 days**         |

---

## Why Use GridKit?

### Problem: TanStack Table Requires Manual Wiring

TanStack Table is headless — it gives you full control, but you must implement everything yourself:

```tsx
// ❌ Tracking row clicks requires useEffect + manual state
const [selectedRow, setSelectedRow] = useState(null);

useEffect(() => {
  // Manual subscription to state changes
  const unsubscribe = table.options.onStateChange?.(state);
  if (state.rowSelection) {
    // Extract what changed
    // Send to analytics
    // Save to backend
    // Update local state
  }
  return unsubscribe;
}, [table]);
```

### Solution: GridKit Adds Event System

```tsx
// ✅ Clean event subscription
table.on('row:select', (e) => {
  analytics.track('row_selected', e.payload);
  api.logAction({ type: 'row_select', ...e.payload });
});
```

**No useEffect. No manual state management. Just events.**

## Key Features

### 1. Event System

Subscribe to table events without `useEffect`:

```tsx
// Subscribe to events
table.on('row:select', (e) => console.log('Selected:', e.payload.rowId));
table.on('sorting:change', (e) => savePreferences(e.payload.sorting));
table.on('filtering:change', (e) => trackFilter(e.payload.filter));

// Emit custom events
table.emit('custom:action', { type: 'export', format: 'csv' });

// Middleware (debounce, logging, validation)
table.use(createDebounceMiddleware({ events: ['sorting:change'], wait: 300 }));
```

**Available events:** `row:select`, `row:create`, `row:update`, `row:delete`, `sorting:change`, `filtering:change`, `pagination:change`

### 2. Plugin System

Add features via plugins — no code changes to your table:

```tsx
import {
  auditLogPlugin,
  analyticsPlugin,
  exportPlugin,
} from '@gridkit/plugins';

const table = createEnhancedTable(tanstackTable, {
  plugins: [
    // Audit logging (GDPR/HIPAA compliance)
    auditLogPlugin({
      destination: '/api/audit',
      events: ['row:create', 'row:update', 'row:delete'],
    }),

    // Analytics (Mixpanel, Amplitude, etc.)
    analyticsPlugin({
      provider: 'mixpanel',
      autoTrack: true,
    }),

    // Export (CSV, Excel, PDF)
    exportPlugin({
      formats: ['csv', 'xlsx', 'pdf'],
    }),
  ],
});
```

**Available plugins:** Audit Log, Analytics, Export

### 3. Performance Monitoring

Track table performance without instrumentation:

```tsx
const table = createEnhancedTable(tanstackTable, {
  performance: {
    budgets: {
      rowModelBuild: 16, // 1 frame @ 60fps
      sorting: 50,
      filtering: 100,
    },
  },
});

// Get metrics
const stats = table.metrics.getOperationStats('getRowModel');
console.log(stats); // { operation: 'getRowModel', count: 145, avgTime: 12.3ms }

// Budget violation alerts
table.on('performance:budgetViolation', (event) => {
  console.warn(
    `${event.operation} exceeded budget: ${event.actual}ms > ${event.budget}ms`
  );
});
```

### 4. Schema Validation

Validate row data with Zod/Yup:

```tsx
import { z } from 'zod';

const userSchema = z.object({
  name: z.string().min(1),
  email: z.string().email(),
  age: z.number().min(0),
});

const table = createEnhancedTable(tanstackTable, {
  validation: {
    mode: 'strict',
    autoFix: true,
  },
});

// Validate a row
const result = await table.validateRow(rowData, userSchema);
if (!result.valid) {
  console.log(result.errors);
}
```

---

## Performance Trade-offs

| Feature                | What It Adds                | Overhead    |
| ---------------------- | --------------------------- | ----------- |
| Event system           | Pub/sub, middleware         | ~2-5ms      |
| Performance monitoring | Metrics, budgets            | ~1-3ms      |
| Validation             | Schema validation           | ~3-7ms      |
| Plugin manager         | Registration, isolation     | ~2-5ms      |
| **Total**              | **All enterprise features** | **~5-15ms** |

For most enterprise apps, this is negligible compared to:

- Network latency (50-500ms)
- Database queries (10-100ms)
- User perception threshold (100ms)

**5-15ms overhead is worth 3 weeks of saved development time.**

---

## API

### createEnhancedTable

```typescript
function createEnhancedTable<TData>(
  tanstackTable: Table<TData>,
  options?: {
    events?: boolean | EventConfig;
    performance?: boolean | PerformanceConfig;
    validation?: boolean | ValidationConfig;
    plugins?: Plugin[];
  }
): EnhancedTable<TData>;
```

**Parameters:**

- `tanstackTable` — Your existing TanStack Table instance
- `options` — Optional features to enable (all optional, defaults to `{}`)

**Returns:** Enhanced table with all TanStack APIs + GridKit features

### EnhancedTable

All TanStack Table methods are preserved. New methods:

```typescript
interface EnhancedTable<TData> extends Table<TData> {
  // Event system
  on(event: string, handler: (e: Event) => void): () => void;
  off(event: string, handler: (e: Event) => void): void;
  emit(event: string, payload: any): void;
  use(middleware: Middleware): void;

  // Performance
  metrics: {
    getOperationStats(operation: string): OperationStats;
    getMetrics(): Metrics;
  };

  // Validation
  validateRow(data: any, schema?: Schema): Promise<ValidationResult>;
  validateAll(): Promise<ValidationReport>;

  // Plugins
  registerPlugin(plugin: Plugin): void;
  unregisterPlugin(id: string): void;
  getPlugin(id: string): Plugin | undefined;
}
```

## Do I Need This?

### Use GridKit If:

- ✅ You need to track user interactions (analytics, audit logs)
- ✅ You want plugins (export, collaboration, offline)
- ✅ You need schema validation for row data
- ✅ You want performance monitoring without manual instrumentation
- ✅ You're building enterprise/compliance-focused apps

### Don't Need GridKit If:

- ❌ You have a simple table with basic sorting/filtering
- ❌ You don't need event tracking or plugins
- ❌ You prefer building everything yourself (TanStack is great!)

## Migration Path

**Good news:** There's no migration. GridKit wraps your existing table:

```tsx
// Before
const tanstackTable = useReactTable({
  columns,
  data,
  getCoreRowModel: getCoreRowModel(),
});

// After (add GridKit)
const table = createEnhancedTable(tanstackTable, { events: true });

// Your rendering code stays the same
table.getHeaderGroups(); // ✅ Still works
table.getRowModel().rows; // ✅ Still works
```

## Documentation

- 🎯 **[Live Demo on CodeSandbox](https://codesandbox.io/p/sandbox/gridkit-exchanged-chykt4)** — Try before you install
- 📖 [Full API Reference](https://github.com/eustatos/gridkit/tree/main/packages/tanstack-adapter)
- 🔌 [Available Plugins](https://www.npmjs.com/package/@gridkit/plugins)

## Related Packages

| Package                                                            | Description                                     |
| ------------------------------------------------------------------ | ----------------------------------------------- |
| [@gridkit/plugins](https://www.npmjs.com/package/@gridkit/plugins) | Official plugins (Audit Log, Analytics, Export) |
| [@gridkit/core](https://www.npmjs.com/package/@gridkit/core)       | Core engine (used internally)                   |

## License

MIT — see [LICENSE](https://github.com/gridkit/eustatos/blob/main/LICENSE)

---

**GitHub:** [github.com/gridkit/gridkit](https://github.com/eustatos/gridkit)