> For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt.

# `MainThreadRef`

A box that keeps a value between calls of your [main-thread scripts](/guide/glossary.md#main-thread-script), such as a tap count or the element a drag started on. `import { createMainThreadRef, MainThreadRef } from '@blotch/angular-lynx';`

:::info
Template handlers such as `(bindtap)` already run on the main thread. [Main-thread scripts](/guide/main-thread/index.md) explains when you need this API instead.
:::

## Usage

```typescript title="src/app/app.ts"
import { Component } from '@angular/core';
import {
  createMainThreadRef,
  LYNX_ELEMENTS,
  LynxMainThreadEvent,
  mainThreadFn,
  type MainThread,
} from '@blotch/angular-lynx';

const taps = createMainThreadRef(0);

const fade = mainThreadFn((event: MainThread.TouchEvent) => {
  taps.current++;
  event.currentTarget.setStyleProperty('opacity', String(1 / taps.current));
});

@Component({
  selector: 'app-root',
  imports: [LYNX_ELEMENTS, LynxMainThreadEvent],
  template: `
    <view [mainThreadBindtap]="fade">
      <text>Tap to fade</text>
    </view>
  `,
})
export class App {
  readonly fade = fade;
}
```

## API

### `createMainThreadRef(initValue)`

```typescript
function createMainThreadRef<T>(initValue: T): MainThreadRef<T>;
```

Creates a ref holding `initValue`. It's the same as `new MainThreadRef(initValue)`.

### `MainThreadRef<T>`

```typescript
class MainThreadRef<T> {
  constructor(initValue: T);
  current: T;
}
```

- **`current`**: the value. Read it and assign to it from your main-thread functions.

## Constraints

- **Each thread has its own copy.** The background thread also loads each file that creates a ref at module scope, so the ref exists there too. A value written on the main thread isn't seen by code on the background thread, and the reverse. Use a ref only from main-thread functions.
- **Passed to a background function, it arrives as the background thread's copy**, the same ref the function would reach through its closure. A ref created in a component has no copy there.
- **Create it at module scope**, next to the functions that use it.
- **Changing it doesn't render anything.** It isn't a signal.

## Related

- [Main-thread scripts guide](/guide/main-thread/index.md)
- [`mainThreadFn`](/api/main-thread/main-thread-fn.md)
- [`LynxMainThreadEvent`](/api/main-thread/main-thread-event.md)
