This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: rn-bridgeless-turbomodule-jsi-hostobject-retention

React Native 0.78 Bridgeless TurboModule JSI Host Object Retention Guardrail

Mandates explicit native teardown semantics and lifecycle coordination for C++ JSI HostObjects in React Native 0.78 Bridgeless mode. Because Hermes GC runs non-deterministically, relying on HostObject C++ destructors for native resources causes memory spikes, native memory exhaustion, and OOM crashes across rapidly unmounted React native views.

Prohibited Anti-Pattern: Relying on Non-Deterministic Hermes Garbage Collection to Free C++ Native Resources in Bridgeless JSI HostObjects

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: React Native 0.78 Bridgeless TurboModule JSI Host Object Retention Guardrail - Mandates explicit native teardown semantics and lifecycle coordination for C++ JSI HostObjects in React Native 0.78 Bridgeless mode. Because Hermes GC runs non-deterministically, relying on HostObject C++ destructors for native resources causes memory spikes, native memory exhaustion, and OOM crashes across rapidly unmounted React native views.
globs: src/**/*.{ts,tsx}, cpp/**/*.{h,cpp}, ios/**/*.{h,m,mm}, android/src/main/jni/**/*.{h,cpp}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/rn-bridgeless-turbomodule-jsi-hostobject-retention"
---

# React Native 0.78 Bridgeless TurboModule JSI Host Object Retention Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Relying on Non-Deterministic Hermes Garbage Collection to Free C++ Native Resources in Bridgeless JSI HostObjects

## System Constraints
You are a Principal Software Architect enforcing React Native 0.78 Bridgeless TurboModule JSI Host Object Retention Guardrails. In React Native 0.78, the Bridgeless architecture directly exposes C++ JSI HostObjects to JavaScript without serialized message queues. You must strictly forbid relying on JavaScript runtime garbage collection (Hermes/V8 finalizers) to release heavy native handles such as graphics contexts, camera buffers, hardware decoders, or thread pools. You mandate deterministic invalidation patterns combining native C++ atomic resource detachment with React component lifecycle cleanup hooks.

## Strict Guidelines
- Engineers MUST ALWAYS expose an explicit `dispose()` or `invalidate()` method on any `jsi::HostObject` holding native handles, buffers, or listeners.
- Engineers MUST NOT rely on JSI `HostObject` C++ destructors (`~HostObject()`) for releasing heavy native resources or unregistering global native observers.
- React components MUST invoke HostObject disposal routines within the synchronous cleanup callback of `useEffect` or `useLayoutEffect`.
- C++ JSI implementations MUST maintain an `std::atomic<bool> isInvalidated_` state and immediately throw a JSI runtime error or safely no-op when methods are invoked on a disposed object.
- TurboModules providing JSI HostObjects MUST implement `TurboModule::invalidate()` to cascade reclamation across all active HostObject instances when the runtime shuts down or reloads.

## Bad vs Good Implementations
### Lifecycle Management for Bridgeless JSI HostObject in React Native Views

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The native HostObject retains heavy video frame buffers in native C++ memory. When this component unmounts rapidly (e.g., during list scrolling or navigation changes), the JS reference drops, but the C++ destructor is only invoked when Hermes performs garbage collection. This causes native memory starvation and application crashes.
```typescript
import React, { useEffect, useState } from 'react';
import { NativeVideoDecoderModule } from './NativeVideoDecoderModule';
import type { VideoFrameHostObject } from './types';

export const VideoPlayerView = ({ streamId }: { streamId: string }) => {
  const [frameObject, setFrameObject] = useState<VideoFrameHostObject | null>(null);

  useEffect(() => {
    // ANTI-PATTERN: Native HostObject is acquired and abandoned on unmount.
    // In Bridgeless RN 0.78, native C++ frame buffers stay retained in memory
    // until Hermes decides to run a full GC cycle, leading to rapid native OOM.
    const nativeBuffer = NativeVideoDecoderModule.acquireFrameBuffer(streamId);
    setFrameObject(nativeBuffer);
  }, [streamId]);

  return <>{/* Rendering frameObject */}</>;
};
```

#### Production Standard (Correct)
> **Standard**: The component cleans up native resources deterministically inside the useEffect teardown callback. Even if Hermes delays JS garbage collection, the underlying C++ native memory handle is detached immediately, preventing memory ballooning.
```typescript
import React, { useEffect } from 'react';
import { NativeVideoDecoderModule } from './NativeVideoDecoderModule';
import type { VideoFrameHostObject } from './types';

export const VideoPlayerView = ({ streamId }: { streamId: string }) => {
  useEffect(() => {
    // ACQUIRE: Deterministic creation of HostObject
    const hostObject: VideoFrameHostObject = NativeVideoDecoderModule.acquireFrameBuffer(streamId);

    return () => {
      // MANDATORY GUARDRAIL: Explicit deterministic disposal on view unmount.
      // Detaches the native buffer and marks the C++ HostObject invalid immediately.
      if (hostObject && !hostObject.isDisposed()) {
        hostObject.dispose();
      }
    };
  }, [streamId]);

  return <>{/* Rendering frame */}</>;
};
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: React Native 0.78 Bridgeless TurboModule JSI Host Object Retention Guardrail

React Native 0.78 Bridgeless TurboModule JSI Host Object Retention Guardrail defines an industrial-grade behavioral standard for mobile engineering. Mandates explicit native teardown semantics and lifecycle coordination for C++ JSI HostObjects in React Native 0.78 Bridgeless mode. Because Hermes GC runs non-deterministically, relying on HostObject C++ destructors for native resources causes memory spikes, native memory exhaustion, and OOM crashes across rapidly unmounted React native views. 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: Relying on Non-Deterministic Hermes Garbage Collection to Free C++ Native Resources in Bridgeless JSI HostObjects 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 DriftRelying on Non-Deterministic Hermes Garbage Collection to Free C++ Native Resources in Bridgeless JSI HostObjectsCritical
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 expose an explicit `dispose()` or `invalidate()` method on any `jsi

Engineers MUST ALWAYS expose an explicit `dispose()` or `invalidate()` method on any `jsi::HostObject` holding native handles, buffers, or listeners.

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 rely on JSI `HostObject` C++ destructors (`~HostObject()`) for releasing heavy native resources or unregistering global native observers.

Engineers MUST NOT rely on JSI `HostObject` C++ destructors (`~HostObject()`) for releasing heavy native resources or unregistering global native observers.

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

React components MUST invoke HostObject disposal routines within the synchronous cleanup callback of `useEffect` or `useLayoutEffect`.

React components MUST invoke HostObject disposal routines within the synchronous cleanup callback of `useEffect` or `useLayoutEffect`.

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

C++ JSI implementations MUST maintain an `std

C++ JSI implementations MUST maintain an `std::atomic<bool> isInvalidated_` state and immediately throw a JSI runtime error or safely no-op when methods are invoked on a disposed object.

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

TurboModules providing JSI HostObjects MUST implement `TurboModule

TurboModules providing JSI HostObjects MUST implement `TurboModule::invalidate()` to cascade reclamation across all active HostObject instances when the runtime shuts down or reloads.

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.78 Bridgeless TurboModule JSI Host Object Retention Guardrail critical for AI coding assistants?

Mandates explicit native teardown semantics and lifecycle coordination for C++ JSI HostObjects in React Native 0.78 Bridgeless mode. Because Hermes GC runs non-deterministically, relying on HostObject C++ destructors for native resources causes memory spikes, native memory exhaustion, and OOM crashes across rapidly unmounted React native views. 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 (Relying on Non-Deterministic Hermes Garbage Collection to Free C++ Native Resources in Bridgeless JSI HostObjects) 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