This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: react-native-turbomodule-jsi-memory-safety

React Native 0.76+ Bridgeless TurboModule JSI Memory Safety & HostObject Lifetime Guardrail

In React Native 0.76+ bridgeless architecture, TurboModules bypass asynchronous serialization and interface directly with C++ JSI runtime heaps. Unmanaged native object references, dangling HostObject pointers, or cross-thread raw JSI access cause uncatchable SIGSEGV crashes, Hermes GC deadlocks, and silent memory leaks across JavaScript-native boundaries.

Prohibited Anti-Pattern: Retaining Raw JSI HostObject Pointers and Capturing Non-Thread-Safe JSI Values Across Async Dispatch Boundaries

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: React Native 0.76+ Bridgeless TurboModule JSI Memory Safety & HostObject Lifetime Guardrail - In React Native 0.76+ bridgeless architecture, TurboModules bypass asynchronous serialization and interface directly with C++ JSI runtime heaps. Unmanaged native object references, dangling HostObject pointers, or cross-thread raw JSI access cause uncatchable SIGSEGV crashes, Hermes GC deadlocks, and silent memory leaks across JavaScript-native boundaries.
globs: src/**/*.{ts,tsx}, android/src/main/jni/**/*.{cpp,h}, ios/**/*.{mm,h,cpp}, specs/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/react-native-turbomodule-jsi-memory-safety"
---

# React Native 0.76+ Bridgeless TurboModule JSI Memory Safety & HostObject Lifetime Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Retaining Raw JSI HostObject Pointers and Capturing Non-Thread-Safe JSI Values Across Async Dispatch Boundaries

## System Constraints
You are a Principal Mobile Architect enforcing React Native 0.76+ Bridgeless TurboModule JSI Memory Safety. Mandate strict synchronous C++ HostObject lifecycle management, thread confinement, and RAII reclamation between JavaScript and native engines.

## Strict Guidelines
- Engineers MUST ALWAYS wrap JSI-exported native allocations inside `std::shared_ptr<facebook::jsi::HostObject>` to ensure predictable RAII destruction when Hermes garbage collects the wrapper.
- Engineers MUST NOT capture raw `jsi::Value`, `jsi::Object`, `jsi::String`, or raw runtime references (`jsi::Runtime&`) across asynchronous thread boundaries or native queue hops.
- Services MUST dispatch mutations and callbacks back to the JavaScript thread using `react::CallInvoker` before accessing or resolving JSI allocations.
- TypeScript interfaces wrapping native HostObjects MUST provide explicit disposal methods (`Symbol.dispose` or `release()`) and integrate with `FinalizationRegistry` to guarantee fallback reclamation of underlying native buffers.
- TurboModule specs MUST strictly declare nullable ownership types and MUST NOT store long-lived strong references to native objects within global JavaScript scope across Fast Refresh cycles.

## Bad vs Good Implementations
### Unsafe Native HostObject Lifetime vs RAII Disposable Pattern in TypeScript Wrapper

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Exposing raw native pointers to JavaScript creates catastrophic vulnerabilities: memory leaks occur if disposal is missed during unmounts or Fast Refresh, and stale pointers cause SIGSEGV crashes if accessed after manual release or native engine resets.
```typescript
import { TurboModuleRegistry } from 'react-native';
import type { TurboModule } from 'react-native';

interface NativeBufferTurboModule extends TurboModule {
  allocateSharedBuffer(sizeBytes: number): number; // Leaks raw memory address pointer
  readBuffer(pointer: number): ArrayBuffer;
  freeBuffer(pointer: number): void;
}

const NativeBuffer = TurboModuleRegistry.getEnforcing<NativeBufferTurboModule>('BufferModule');

// ANTI-PATTERN: Raw integer pointer stored in global state. Relies solely on developer calling freeBuffer.
// Fast Refresh, crashes, or unhandled errors leak memory permanently without Hermes GC hooks.
export class LeakyNativeBuffer {
  private nativePtr: number;

  constructor(size: number) {
    this.nativePtr = NativeBuffer.allocateSharedBuffer(size);
  }

  public getData(): ArrayBuffer {
    return NativeBuffer.readBuffer(this.nativePtr);
  }
  // If component unmounts without calling dispose, native memory leaks permanently
}
```

#### Production Standard (Correct)
> **Standard**: Implements RAII in TypeScript using `Symbol.dispose` for deterministic cleanup along with a fallback `FinalizationRegistry` to guarantee underlying C++ HostObject memory reclamation even if JS developers miss manual disposal.
```typescript
import { TurboModuleRegistry } from 'react-native';
import type { TurboModule } from 'react-native';

interface NativeBufferSpec extends TurboModule {
  createManagedBuffer(sizeBytes: number): { readonly __brand: unique symbol };
  readManagedBuffer(handle: object): ArrayBuffer;
  releaseManagedBuffer(handle: object): void;
}

const NativeBuffer = TurboModuleRegistry.getEnforcing<NativeBufferSpec>('ManagedBufferModule');

const registry = new FinalizationRegistry((handle: object) => {
  NativeBuffer.releaseManagedBuffer(handle);
});

export class SafeNativeBuffer implements Disposable {
  private handle: object | null;

  constructor(sizeBytes: number) {
    if (sizeBytes <= 0 || !Number.isSafeInteger(sizeBytes)) {
      throw new RangeError(`Invalid buffer allocation size: ${sizeBytes}`);
    }
    const nativeHostObject = NativeBuffer.createManagedBuffer(sizeBytes);
    this.handle = nativeHostObject;
    registry.register(this, nativeHostObject, this);
  }

  public getData(): ArrayBuffer {
    if (!this.handle) {
      throw new Error('Attempted to read from a released native buffer');
    }
    return NativeBuffer.readManagedBuffer(this.handle);
  }

  public [Symbol.dispose](): void {
    if (this.handle) {
      registry.unregister(this);
      NativeBuffer.releaseManagedBuffer(this.handle);
      this.handle = null;
    }
  }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: React Native 0.76+ Bridgeless TurboModule JSI Memory Safety & HostObject Lifetime Guardrail

React Native 0.76+ Bridgeless TurboModule JSI Memory Safety & HostObject Lifetime Guardrail defines an industrial-grade behavioral standard for mobile engineering. In React Native 0.76+ bridgeless architecture, TurboModules bypass asynchronous serialization and interface directly with C++ JSI runtime heaps. Unmanaged native object references, dangling HostObject pointers, or cross-thread raw JSI access cause uncatchable SIGSEGV crashes, Hermes GC deadlocks, and silent memory leaks across JavaScript-native boundaries. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Retaining Raw JSI HostObject Pointers and Capturing Non-Thread-Safe JSI Values Across Async Dispatch Boundaries Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftRetaining Raw JSI HostObject Pointers and Capturing Non-Thread-Safe JSI Values Across Async Dispatch BoundariesCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS wrap JSI-exported native allocations inside `std

Engineers MUST ALWAYS wrap JSI-exported native allocations inside `std::shared_ptr<facebook::jsi::HostObject>` to ensure predictable RAII destruction when Hermes garbage collects the wrapper.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST NOT capture raw `jsi

Engineers MUST NOT capture raw `jsi::Value`, `jsi::Object`, `jsi::String`, or raw runtime references (`jsi::Runtime&`) across asynchronous thread boundaries or native queue hops.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Services MUST dispatch mutations and callbacks back to the JavaScript thread using `react

Services MUST dispatch mutations and callbacks back to the JavaScript thread using `react::CallInvoker` before accessing or resolving JSI allocations.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

TypeScript interfaces wrapping native HostObjects MUST provide explicit disposal methods (`Symbol.dispose` or `release()`) and integrate with `FinalizationRegistry` to guarantee fallback reclamation of underlying native buffers.

TypeScript interfaces wrapping native HostObjects MUST provide explicit disposal methods (`Symbol.dispose` or `release()`) and integrate with `FinalizationRegistry` to guarantee fallback reclamation of underlying native buffers.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

TurboModule specs MUST strictly declare nullable ownership types and MUST NOT store long-lived strong references to native objects within global JavaScript scope across Fast Refresh cycles.

TurboModule specs MUST strictly declare nullable ownership types and MUST NOT store long-lived strong references to native objects within global JavaScript scope across Fast Refresh cycles.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is React Native 0.76+ Bridgeless TurboModule JSI Memory Safety & HostObject Lifetime Guardrail critical for AI coding assistants?

In React Native 0.76+ bridgeless architecture, TurboModules bypass asynchronous serialization and interface directly with C++ JSI runtime heaps. Unmanaged native object references, dangling HostObject pointers, or cross-thread raw JSI access cause uncatchable SIGSEGV crashes, Hermes GC deadlocks, and silent memory leaks across JavaScript-native boundaries. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Retaining Raw JSI HostObject Pointers and Capturing Non-Thread-Safe JSI Values Across Async Dispatch Boundaries) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

Related MOBILE Rules

View all rules →
1 Rule in Stack

React