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

React Native 0.76+ JSI HostObject Native Memory Lifecycle Invariant

Enforces deterministic reference retention, cross-thread synchronization, and explicit disposal protocols for C++ jsi::HostObject instances bridged to Hermes in React Native 0.76+. Eliminates fatal use-after-free (UAF) and SIGSEGV native memory faults caused by asynchronous worker threads accessing garbage-collected or runtime-invalidated native handles.

Prohibited Anti-Pattern: Accessing Dangling jsi::HostObject Native Handles Across Async Boundaries Without Atomic Invalidation and Runtime Guarding

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: React Native 0.76+ JSI HostObject Native Memory Lifecycle Invariant - Enforces deterministic reference retention, cross-thread synchronization, and explicit disposal protocols for C++ jsi::HostObject instances bridged to Hermes in React Native 0.76+. Eliminates fatal use-after-free (UAF) and SIGSEGV native memory faults caused by asynchronous worker threads accessing garbage-collected or runtime-invalidated native handles.
globs: src/**/*.{ts,tsx}, cpp/**/*.{h,cpp}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/react-native-76-jsi-hostobject-lifecycle-guardrail"
---

# React Native 0.76+ JSI HostObject Native Memory Lifecycle Invariant

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Accessing Dangling jsi::HostObject Native Handles Across Async Boundaries Without Atomic Invalidation and Runtime Guarding

## System Constraints
You are a Principal Software Architect enforcing zero-tolerance native memory safety for React Native 0.76+ New Architecture and Hermes JSI bindings. You must mandate strict memory ownership invariants around jsi::HostObject instances, eliminating double-free and use-after-free native memory faults by strictly gating the lifecycle of C++ HostObjects shared across Hermes GC and native thread boundaries.

## Strict Guidelines
- Engineers MUST ALWAYS wrap shared native HostObject pointers in thread-safe atomic handles (std::shared_ptr with std::atomic flags or explicit lifetime tokens) to prevent worker threads from accessing objects unseated by Hermes GC sweeps.
- Engineers MUST NOT capture raw native HostObject pointers or jsi::Runtime references inside asynchronous C++ lambdas, std::thread, dispatch_async, or thread-pool tasks.
- Code MUST expose an explicit disposal contract (e.g., .dispose() or Symbol.dispose) on the TypeScript boundary to guarantee deterministic native teardown rather than relying on non-deterministic Hermes GC finalization.
- Services MUST verify host object validity via an internal atomic alive-check guard prior to executing any native method invoked from JavaScript.
- Components NEVER hold unmanaged long-lived references to native JSI HostObjects across React component unmount boundaries without executing lifecycle teardown in cleanup hooks.

## Bad vs Good Implementations
### JSI HostObject Bridge: Dangling Async Pointer vs Deterministic Lifetime Token Guard

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The native context is released abruptly in the unmount cleanup while computeBuffer may still execute across thread boundaries in native C++ code. The Hermes GC may clean up the JavaScript wrapper while the native background worker attempts to read the underlying raw pointer, leading to a SIGSEGV / use-after-free crash.
```typescript
import { useEffect } from 'react';

// Native TurboModule exposes a direct JSI HostObject reference
declare const NativeVectorEngine: {
  createContext(): { computeBuffer(id: number): Promise<Float32Array>; release(): void };
};

export function useVectorProcessor() {
  useEffect(() => {
    // ANTI-PATTERN: Leaking native HostObject reference into async closures.
    // If the component unmounts or Hermes triggers generational GC before
    // the async computation completes on a native worker thread,
    // native code dereferences a deallocated jsi::HostObject, causing SIGSEGV.
    const context = NativeVectorEngine.createContext();

    const runWorkload = async () => {
      const result = await context.computeBuffer(42);
      console.log('Processed buffer length:', result.byteLength);
    };

    runWorkload();

    return () => {
      // Implicit or misplaced native release without invalidating in-flight tasks
      context.release();
    };
  }, []);
}
```

#### Production Standard (Correct)
> **Standard**: Guarantees deterministic lifecycle boundaries using an AbortController and explicit handle disposal. On the native C++ layer, the corresponding HostObject checks an atomic cancellation token before accessing memory, preventing use-after-free and double-free conditions if GC or unmount occurs mid-computation.
```typescript
import { useEffect, useRef } from 'react';

interface NativeVectorContext {
  readonly isDisposed: boolean;
  computeBuffer(id: number): Promise<Float32Array>;
  dispose(): void;
}

declare const NativeVectorEngine: {
  createContext(): NativeVectorContext;
};

export function useVectorProcessor() {
  const contextRef = useRef<NativeVectorContext | null>(null);
  const abortControllerRef = useRef<AbortController | null>(null);

  useEffect(() => {
    // PRODUCTION FIX: Deterministic lifecycle gated via ref and AbortController.
    // Native HostObject enforces internal std::weak_ptr/atomic lifetime token checks,
    // and the TS layer prevents calling invalid handles post-unmount.
    const context = NativeVectorEngine.createContext();
    contextRef.current = context;
    const abortController = new AbortController();
    abortControllerRef.current = abortController;

    const runWorkload = async () => {
      try {
        if (abortController.signal.aborted || context.isDisposed) {
          return;
        }
        const result = await context.computeBuffer(42);
        if (!abortController.signal.aborted) {
          console.log('Processed buffer length:', result.byteLength);
        }
      } catch (error) {
        if (!abortController.signal.aborted) {
          console.error('Vector processing failed:', error);
        }
      }
    };

    void runWorkload();

    return () => {
      abortController.abort();
      if (contextRef.current && !contextRef.current.isDisposed) {
        // Explicit native teardown invalidates atomic handles safely
        contextRef.current.dispose();
        contextRef.current = null;
      }
    };
  }, []);
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: React Native 0.76+ JSI HostObject Native Memory Lifecycle Invariant

React Native 0.76+ JSI HostObject Native Memory Lifecycle Invariant defines an industrial-grade behavioral standard for mobile engineering. Enforces deterministic reference retention, cross-thread synchronization, and explicit disposal protocols for C++ jsi::HostObject instances bridged to Hermes in React Native 0.76+. Eliminates fatal use-after-free (UAF) and SIGSEGV native memory faults caused by asynchronous worker threads accessing garbage-collected or runtime-invalidated native handles. 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: Accessing Dangling jsi::HostObject Native Handles Across Async Boundaries Without Atomic Invalidation and Runtime Guarding 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 DriftAccessing Dangling jsi::HostObject Native Handles Across Async Boundaries Without Atomic Invalidation and Runtime GuardingCritical
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 shared native HostObject pointers in thread-safe atomic handles (std

Engineers MUST ALWAYS wrap shared native HostObject pointers in thread-safe atomic handles (std::shared_ptr with std::atomic flags or explicit lifetime tokens) to prevent worker threads from accessing objects unseated by Hermes GC sweeps.

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 native HostObject pointers or jsi

Engineers MUST NOT capture raw native HostObject pointers or jsi::Runtime references inside asynchronous C++ lambdas, std::thread, dispatch_async, or thread-pool tasks.

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

Code MUST expose an explicit disposal contract (e.g., .dispose() or Symbol.dispose) on the TypeScript boundary to guarantee deterministic native teardown rather than relying on non-deterministic Hermes GC finalization.

Code MUST expose an explicit disposal contract (e.g., .dispose() or Symbol.dispose) on the TypeScript boundary to guarantee deterministic native teardown rather than relying on non-deterministic Hermes GC finalization.

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

Services MUST verify host object validity via an internal atomic alive-check guard prior to executing any native method invoked from JavaScript.

Services MUST verify host object validity via an internal atomic alive-check guard prior to executing any native method invoked from JavaScript.

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

Components NEVER hold unmanaged long-lived references to native JSI HostObjects across React component unmount boundaries without executing lifecycle teardown in cleanup hooks.

Components NEVER hold unmanaged long-lived references to native JSI HostObjects across React component unmount boundaries without executing lifecycle teardown in cleanup hooks.

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+ JSI HostObject Native Memory Lifecycle Invariant critical for AI coding assistants?

Enforces deterministic reference retention, cross-thread synchronization, and explicit disposal protocols for C++ jsi::HostObject instances bridged to Hermes in React Native 0.76+. Eliminates fatal use-after-free (UAF) and SIGSEGV native memory faults caused by asynchronous worker threads accessing garbage-collected or runtime-invalidated native handles. 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 (Accessing Dangling jsi::HostObject Native Handles Across Async Boundaries Without Atomic Invalidation and Runtime Guarding) 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