1import { useEffect } from "react";
2import { AppState } from "react-native";
3import { scheduleOnUI } from "react-native-worklets";
4
5function collectUiRuntimeGarbage() {
6 "worklet";
7 // Hermes exposes `gc` on the worklets UI runtime; skip quietly on runtimes that do not.
8 const gc = (globalThis as { gc?: () => void }).gc;
9 if (typeof gc === "function") gc();
10}
11
12/**
13 * React Native only collects the main JS runtime on an iOS memory warning. The
14 * worklets UI runtime is a separate Hermes heap that holds native shadow nodes and
15 * serializables alive until its own GC runs, so collect it on the same warning.
16 */
17export function useUiRuntimeMemoryWarningGc() {
18 useEffect(() => {
19 const subscription = AppState.addEventListener("memoryWarning", () => {
20 scheduleOnUI(collectUiRuntimeGarbage);
21 });
22 return () => subscription.remove();
23 }, []);
24}