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

# useSimData & Socket Hooks

> Real-time simulator data and socket event hooks.

This page covers all Socket.io-based hooks exported from the SDK. The primary hook for most plugins is `useSimData`. The lower-level hooks (`useSocket`, `useSimulatorData`, etc.) are available when you need direct event access.

## Import

```ts theme={null}
import {
  useSimData,
  useSocket,
  useSimulatorData,
  useProtocolUrl,
  useNotifications,
  useSystemMetrics,
} from "@skyvexsoftware/stratos-sdk";
```

***

## `useSimData`

TanStack Query + Socket.io hook for real-time simulator data. Hydrates from `GET /api/simulator/snapshot` on mount, then subscribes to `simulator:data` and `simulator:status` events via Socket.io.

**Performance:** Simulator data arrives at 10–20 Hz. Updates are buffered and flushed via `requestAnimationFrame`, aligning cache writes to the browser's \~60 fps paint cycle. Multiple components share a single TanStack Query cache entry — there is no duplicate subscription overhead.

### Signature

```ts theme={null}
function useSimData<TSelected = SimDataSnapshot>(
  options?: UseSimDataOptions<TSelected>
): UseSimDataReturn<TSelected>

type UseSimDataOptions<TSelected = SimDataSnapshot> = {
  select?: (snapshot: SimDataSnapshot) => TSelected;
};

type UseSimDataReturn<TSelected = SimDataSnapshot> = {
  data: TSelected;
  isLoading: boolean;
};
```

### Parameters

| Parameter        | Type                                       | Description                                                                       |
| ---------------- | ------------------------------------------ | --------------------------------------------------------------------------------- |
| `options.select` | `(snapshot: SimDataSnapshot) => TSelected` | Selector function. The component only re-renders when the selected value changes. |

### `SimDataSnapshot`

See [`SimDataSnapshot`](/sdk/type-reference#simdatasnapshot) for the full shape. `FlightData` (the nested `data` field) contains all simulator variables: position, speed, altitude, heading, engine data, fuel, weather, flaps, gear, and more.

### Engine state

Each engine exposes raw data (`engine1Firing`, `engine1N1`, `engine1N2`, `engine1PctRpm`) and a composite boolean:

```ts theme={null}
engine1On: boolean; // true when N1 > 5% or PctRpm > 5%
engine2On: boolean;
engine3On: boolean;
engine4On: boolean;
```

`engine*On` is the recommended way to check whether an engine is running. It works reliably across all aircraft types (jets, turboprops, helicopters, pistons) and both MSFS and X-Plane. The raw `engine*Firing` (combustion) field is still available but can produce false positives during startup/shutdown on some aircraft.

### Usage

```tsx theme={null}
// Full snapshot — re-renders on any field change
const { data, isLoading } = useSimData();

if (!isLoading && data?.isConnected) {
  console.log(data.data?.altitude);
}
```

```tsx theme={null}
// Position selector — re-renders only when lat/lon/heading change
const { data: pos } = useSimData({
  select: (s) => ({
    lat: s.data?.latitude ?? 0,
    lon: s.data?.longitude ?? 0,
    hdg: s.data?.heading ?? 0,
  }),
});
```

```tsx theme={null}
// Single scalar — re-renders only when altitude changes
const { data: altitude } = useSimData({
  select: (s) => s.data?.altitude ?? 0,
});
```

***

## `useSocket`

Core Socket.io connection hook. Uses a singleton `SocketManager` — all consumers share a single underlying socket. The socket connects when the first subscriber mounts and disconnects one second after the last subscriber unmounts.

### Signature

```ts theme={null}
function useSocket(): UseSocketReturn

type UseSocketReturn = {
  socket: Socket | null;
  isConnected: boolean;
  connectionState: ConnectionState;  // "disconnected" | "connecting" | "connected" | "error"
  clientId: string | null;
  connect: () => void;
  disconnect: () => void;
  subscribe: (eventType: string) => void;
  unsubscribe: (eventType: string) => void;
};
```

### Usage

```tsx theme={null}
function ConnectionStatus() {
  const { isConnected, connectionState } = useSocket();

  return <span>{connectionState}</span>;
}
```

***

## `useSimulatorData`

Raw event streaming hook. Calls your callbacks directly on each `simulator:data` and `simulator:status` event. Prefer `useSimData` unless you need the raw payload or must bypass TanStack Query caching.

### Signature

```ts theme={null}
function useSimulatorData(
  onData?: (payload: SimulatorDataPayload) => void,
  onStatus?: (payload: SimulatorStatusPayload) => void,
): {
  isConnected: boolean;
  latestData: SimulatorDataPayload | null;
  simulatorStatus: SimulatorStatusPayload | null;
}
```

### Usage

```tsx theme={null}
const logger = usePluginLogger();

const { latestData, isConnected } = useSimulatorData(
  (payload) => logger.debug("SimData", "Received data", payload),
  (status) => logger.info("SimData", "Status changed", status),
);
```

***

## `useProtocolUrl`

Receives deep link events dispatched when the OS opens a `stratos://` URL while the app is running.

### Signature

```ts theme={null}
function useProtocolUrl(
  onProtocolUrl?: (payload: ProtocolUrlPayload) => void,
): ProtocolUrlPayload | null
```

### Usage

```tsx theme={null}
const latestUrl = useProtocolUrl((payload) => {
  console.log("Received protocol URL:", payload.fullUrl);
});
```

***

## `useNotifications`

Accumulates shell notification events for the duration of the component's lifetime.

### Signature

```ts theme={null}
function useNotifications(
  onNotification?: (payload: NotificationPayload) => void,
): {
  notifications: NotificationPayload[];
  clearNotifications: () => void;
}
```

### Usage

```tsx theme={null}
const { notifications, clearNotifications } = useNotifications();

return (
  <ul>
    {notifications.map((n, i) => <li key={i}>{n.message}</li>)}
  </ul>
);
```

***

## `useSystemMetrics`

Streams system metrics (CPU, memory, etc.) from the shell process.

### Signature

```ts theme={null}
function useSystemMetrics(
  onMetrics?: (payload: SystemMetricsPayload) => void,
): {
  isConnected: boolean;
  metrics: SystemMetricsPayload | null;
}
```

### Usage

```tsx theme={null}
const { metrics } = useSystemMetrics();

return <span>CPU: {metrics?.cpu?.percentage ?? 0}%</span>;
```
