This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: capacitor-7-jsi-bridge-retention-guardrail

Capacitor 7 Native Bridge JSI Reference Retention & Listener Teardown Guardrail

Enforces strict lifecycle management and explicit teardown of native plugin event listeners across Capacitor 7 native bridges. Prevents cross-runtime heap memory leaks in Android (V8) and iOS (JavaScriptCore) caused by circular retained references across JSI bridging boundaries.

Prohibited Anti-Pattern: Dangling PluginListenerHandle References Retaining Native-to-JS Bridge Callbacks Across Component Lifecycles

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Native Bridge JSI Reference Retention & Listener Teardown Guardrail - Enforces strict lifecycle management and explicit teardown of native plugin event listeners across Capacitor 7 native bridges. Prevents cross-runtime heap memory leaks in Android (V8) and iOS (JavaScriptCore) caused by circular retained references across JSI bridging boundaries.
globs: src/**/*.{ts,tsx,js,jsx}, ios/App/App/**/*.swift, android/app/src/main/java/**/*.java
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-jsi-bridge-retention-guardrail"
---

# Capacitor 7 Native Bridge JSI Reference Retention & Listener Teardown Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Dangling PluginListenerHandle References Retaining Native-to-JS Bridge Callbacks Across Component Lifecycles

## System Constraints
You are a Principal Mobile Architect enforcing Capacitor 7 Native Bridge JSI Reference Retention Guardrails. You must mandate deterministic listener registration, explicit Promise-resolved PluginListenerHandle teardown, and strict elimination of closure retention cycles between the JavaScript VM (V8/JavaScriptCore) and native Android/iOS bridge hosts.

## Strict Guidelines
- Engineers MUST ALWAYS store the `PluginListenerHandle` returned by `addListener` and invoke its `remove()` method on component unmount or state teardown.
- Engineers MUST NOT rely on component scope garbage collection to tear down native bridge listeners, as the native runtime maintains a root reference to the callback ID.
- Code MUST handle the asynchronous nature of `addListener` in Capacitor 7, ensuring teardown logic awaits resolution or queues `remove()` on an unmounted state flag.
- Services MUST implement explicit `destroy()` or `dispose()` methods that invoke `removeAllListeners()` on the underlying Capacitor plugin instance during module destruction.
- Components NEVER capture un-scoped closure references to mutable external DOM nodes, context providers, or large state trees inside persistent plugin callbacks.

## Bad vs Good Implementations
### Capacitor 7 Native Listener Registration and Teardown in React Lifecycle

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: In Capacitor 7, `addListener` returns a `Promise<PluginListenerHandle>`. Ignoring this handle prevents the native bridge from deallocating the JS callback reference inside the native host, producing a permanent native-to-web memory leak upon unmounting.
```typescript
import React, { useEffect } from 'react';
import { App } from '@capacitor/app';

export const AppStateTracker: React.FC = () => {
  useEffect(() => {
    // ANTI-PATTERN: Discarding the Promise<PluginListenerHandle>.
    // Native bridge keeps callback in JavaScriptCore/V8 root set,
    // leaking component closures and memory on each remount.
    App.addListener('appStateChange', (state) => {
      console.log('App state changed:', state.isActive);
    });
  }, []);

  return <div>Tracking App State</div>;
};
```

#### Production Standard (Correct)
> **Standard**: Correctly coordinates asynchronous listener handle resolution with the component lifecycle. If unmounting occurs before the promise resolves, it immediately invokes `remove()` to purge bridge callback registries in the native host.
```typescript
import React, { useEffect } from 'react';
import { App } from '@capacitor/app';
import type { PluginListenerHandle } from '@capacitor/core';

export const AppStateTracker: React.FC = () => {
  useEffect(() => {
    let isMounted = true;
    let handle: PluginListenerHandle | null = null;

    const setupListener = async () => {
      const listenerHandle = await App.addListener('appStateChange', (state) => {
        if (!isMounted) return;
        console.log('App state changed:', state.isActive);
      });

      if (!isMounted) {
        await listenerHandle.remove();
      } else {
        handle = listenerHandle;
      }
    };

    setupListener();

    return () => {
      isMounted = false;
      if (handle) {
        void handle.remove();
      }
    };
  }, []);

  return <div>Tracking App State</div>;
};
```

Recommended MCP Servers (mcp-serverlist.com)

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

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Capacitor 7 Native Bridge JSI Reference Retention & Listener Teardown Guardrail

Capacitor 7 Native Bridge JSI Reference Retention & Listener Teardown Guardrail defines an industrial-grade behavioral standard for mobile engineering. Enforces strict lifecycle management and explicit teardown of native plugin event listeners across Capacitor 7 native bridges. Prevents cross-runtime heap memory leaks in Android (V8) and iOS (JavaScriptCore) caused by circular retained references across JSI bridging 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: Dangling PluginListenerHandle References Retaining Native-to-JS Bridge Callbacks Across Component Lifecycles 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 DriftDangling PluginListenerHandle References Retaining Native-to-JS Bridge Callbacks Across Component LifecyclesCritical
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 store the `PluginListenerHandle` returned by `addListener` and invoke its `remove()` method on component unmount or state teardown.

Engineers MUST ALWAYS store the `PluginListenerHandle` returned by `addListener` and invoke its `remove()` method on component unmount or state teardown.

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 component scope garbage collection to tear down native bridge listeners, as the native runtime maintains a root reference to the callback ID.

Engineers MUST NOT rely on component scope garbage collection to tear down native bridge listeners, as the native runtime maintains a root reference to the callback ID.

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 handle the asynchronous nature of `addListener` in Capacitor 7, ensuring teardown logic awaits resolution or queues `remove()` on an unmounted state flag.

Code MUST handle the asynchronous nature of `addListener` in Capacitor 7, ensuring teardown logic awaits resolution or queues `remove()` on an unmounted state flag.

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 implement explicit `destroy()` or `dispose()` methods that invoke `removeAllListeners()` on the underlying Capacitor plugin instance during module destruction.

Services MUST implement explicit `destroy()` or `dispose()` methods that invoke `removeAllListeners()` on the underlying Capacitor plugin instance during module destruction.

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 capture un-scoped closure references to mutable external DOM nodes, context providers, or large state trees inside persistent plugin callbacks.

Components NEVER capture un-scoped closure references to mutable external DOM nodes, context providers, or large state trees inside persistent plugin callbacks.

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 Capacitor 7 Native Bridge JSI Reference Retention & Listener Teardown Guardrail critical for AI coding assistants?

Enforces strict lifecycle management and explicit teardown of native plugin event listeners across Capacitor 7 native bridges. Prevents cross-runtime heap memory leaks in Android (V8) and iOS (JavaScriptCore) caused by circular retained references across JSI bridging 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 (Dangling PluginListenerHandle References Retaining Native-to-JS Bridge Callbacks Across Component Lifecycles) 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

Capacitor