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

React Native Bridgeless Fabric JSI Host Object Lifetime & Teardown Guardrail

Prevents C++ host-object use-after-free and dangling pointer memory corruption during rapid unmount-remount cycles within React Native Bridgeless Fabric architecture. Enforces synchronous teardown semantics, cancellation tokens, and explicit nullification of raw JSI object references before the JavaScript runtime context detaches from the shadow tree. Eliminates asynchronous callback re-entry crashes caused by unpinned C++ Turbomodule instances.

Prohibited Anti-Pattern: Asynchronous invocation of raw JSI C++ HostObjects across unmount-remount cycles without cancellation or reference-pinning checks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: React Native Bridgeless Fabric JSI Host Object Lifetime & Teardown Guardrail - Prevents C++ host-object use-after-free and dangling pointer memory corruption during rapid unmount-remount cycles within React Native Bridgeless Fabric architecture. Enforces synchronous teardown semantics, cancellation tokens, and explicit nullification of raw JSI object references before the JavaScript runtime context detaches from the shadow tree. Eliminates asynchronous callback re-entry crashes caused by unpinned C++ Turbomodule instances.
globs: src/**/*.{ts,tsx}, packages/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/react-native-bridgeless-fabric-jsi-memory-lifetime-guardrail"
---

# React Native Bridgeless Fabric JSI Host Object Lifetime & Teardown Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Asynchronous invocation of raw JSI C++ HostObjects across unmount-remount cycles without cancellation or reference-pinning checks

## System Constraints
You are a Principal Mobile Architect enforcing absolute memory safety in React Native Bridgeless Fabric applications interacting with C++ JSI Turbomodules and HostObjects. Mandate explicit lifetime guards, teardown abort tokens, and zero-trust verification around direct JSI pointers to prevent SIGSEGV and heap-use-after-free errors during rapid view hierarchy churn.

## Strict Guidelines
- Engineers MUST ALWAYS invalidate C++ HostObject handles inside the synchronous cleanup phase of useEffect/useLayoutEffect before the native C++ Fabric shadow node is destroyed.
- Engineers MUST NOT capture raw JSI host object references inside unresolved Promises, microtasks, or setTimeout chains that outlive the hosting component lifecycle.
- Code SHOULD utilize AbortController or generation-keyed atomic tokens to gate incoming JSI callbacks against stale component mount iterations.
- Services MUST guard every direct native Turbomodule method invocation with an explicit nullability and liveness check on the underlying HostObject handle.
- Components NEVER invoke asynchronous methods on native JSI HostObjects during or immediately following an unmount event.

## Bad vs Good Implementations
### JSI C++ HostObject Lifetime Handling During Rapid Unmount

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Holding a direct C++ JSI HostObject across intervals without synchronous invalidation flags leads to SIGSEGV crashes when Fabric unbinds the native runtime and frees memory before the JS interval finishes executing its current tick.
```typescript
import React, { useEffect } from 'react';
import { NativeDirectStreamModule } from './NativeDirectStreamModule';

interface StreamProps {
  streamId: string;
}

export const VideoStreamView: React.FC<StreamProps> = ({ streamId }) => {
  useEffect(() => {
    // ANTI-PATTERN: Retaining raw C++ JSI HostObject reference across async boundaries
    // Rapid unmount/remount causes NativeDirectStreamModule's underlying C++ instance
    // to be deallocated by Fabric while processFrame retains a dangling JSI pointer,
    // leading to a fatal heap-use-after-free SIGSEGV.
    const hostSession = NativeDirectStreamModule.createSession(streamId);

    const interval = setInterval(async () => {
      const frame = await hostSession.acquireNextFrame();
      NativeDirectStreamModule.renderFrame(frame);
    }, 16);

    return () => {
      clearInterval(interval);
      hostSession.close(); // Asynchronous C++ cleanup race condition
    };
  }, [streamId]);

  return null;
};
```

#### Production Standard (Correct)
> **Standard**: Implements cooperative lifetime abort signaling, asserts JSI host-object validity before each execution, and guarantees deterministic synchronous release of the C++ HostObject during the unmount cleanup pass.
```typescript
import React, { useEffect, useRef } from 'react';
import { NativeDirectStreamModule, type HostStreamSession } from './NativeDirectStreamModule';

interface StreamProps {
  streamId: string;
}

export const VideoStreamView: React.FC<StreamProps> = ({ streamId }) => {
  const sessionRef = useRef<HostStreamSession | null>(null);

  useEffect(() => {
    const abortController = new AbortController();
    const { signal } = abortController;
    let isMounted = true;

    // Guard against uninitialized or destroyed Bridgeless Turbomodule
    if (!NativeDirectStreamModule?.createSession) {
      return;
    }

    const hostSession = NativeDirectStreamModule.createSession(streamId);
    sessionRef.current = hostSession;

    const pollFrames = async () => {
      while (isMounted && !signal.aborted) {
        try {
          if (!sessionRef.current?.isValid()) {
            break;
          }
          const frame = await sessionRef.current.acquireNextFrame();
          if (!isMounted || signal.aborted) {
            break;
          }
          NativeDirectStreamModule.renderFrame(frame);
        } catch (error: unknown) {
          if (signal.aborted) return;
          console.error('Frame acquisition error:', error);
          break;
        }
      }
    };

    void pollFrames();

    return () => {
      isMounted = false;
      abortController.abort();
      // Synchronous explicit JSI teardown to prevent C++ dangling references
      if (sessionRef.current) {
        sessionRef.current.invalidateSynchronously();
        sessionRef.current = null;
      }
    };
  }, [streamId]);

  return null;
};
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: React Native Bridgeless Fabric JSI Host Object Lifetime & Teardown Guardrail

React Native Bridgeless Fabric JSI Host Object Lifetime & Teardown Guardrail defines an industrial-grade behavioral standard for mobile engineering. Prevents C++ host-object use-after-free and dangling pointer memory corruption during rapid unmount-remount cycles within React Native Bridgeless Fabric architecture. Enforces synchronous teardown semantics, cancellation tokens, and explicit nullification of raw JSI object references before the JavaScript runtime context detaches from the shadow tree. Eliminates asynchronous callback re-entry crashes caused by unpinned C++ Turbomodule instances. 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: Asynchronous invocation of raw JSI C++ HostObjects across unmount-remount cycles without cancellation or reference-pinning checks 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 DriftAsynchronous invocation of raw JSI C++ HostObjects across unmount-remount cycles without cancellation or reference-pinning checksCritical
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 invalidate C++ HostObject handles inside the synchronous cleanup phase of useEffect/useLayoutEffect before the native C++ Fabric shadow node is destroyed.

Engineers MUST ALWAYS invalidate C++ HostObject handles inside the synchronous cleanup phase of useEffect/useLayoutEffect before the native C++ Fabric shadow node is destroyed.

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 host object references inside unresolved Promises, microtasks, or setTimeout chains that outlive the hosting component lifecycle.

Engineers MUST NOT capture raw JSI host object references inside unresolved Promises, microtasks, or setTimeout chains that outlive the hosting component lifecycle.

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 SHOULD utilize AbortController or generation-keyed atomic tokens to gate incoming JSI callbacks against stale component mount iterations.

Code SHOULD utilize AbortController or generation-keyed atomic tokens to gate incoming JSI callbacks against stale component mount iterations.

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 guard every direct native Turbomodule method invocation with an explicit nullability and liveness check on the underlying HostObject handle.

Services MUST guard every direct native Turbomodule method invocation with an explicit nullability and liveness check on the underlying HostObject handle.

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 invoke asynchronous methods on native JSI HostObjects during or immediately following an unmount event.

Components NEVER invoke asynchronous methods on native JSI HostObjects during or immediately following an unmount event.

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 Bridgeless Fabric JSI Host Object Lifetime & Teardown Guardrail critical for AI coding assistants?

Prevents C++ host-object use-after-free and dangling pointer memory corruption during rapid unmount-remount cycles within React Native Bridgeless Fabric architecture. Enforces synchronous teardown semantics, cancellation tokens, and explicit nullification of raw JSI object references before the JavaScript runtime context detaches from the shadow tree. Eliminates asynchronous callback re-entry crashes caused by unpinned C++ Turbomodule instances. 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 (Asynchronous invocation of raw JSI C++ HostObjects across unmount-remount cycles without cancellation or reference-pinning checks) 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