gc-hook is a utility library that simplifies the use of JavaScript's `FinalizationRegistry` for managing object lifecycle and reacting to garbage collection. The current stable version is 0.4.1, with the last publish being a year ago, suggesting a mature but not rapidly evolving codebase. It differentiates itself by addressing common pitfalls associated with `FinalizationRegistry`, such as preventing accidental leaks of the registered reference, allowing flexible proxy overrides, and providing mechanisms for explicit deregistration via held references or tokens. Its primary goal is to abstract away the complex specifics of `FinalizationRegistry`, enabling developers to focus on application logic rather than the intricacies of memory management. It works in both CommonJS and ES module environments, offering broad compatibility.
npm install gc-hookVerified import paths — ran on the pinned version, not inferred.
Demonstrates how to use `create` to register an object with a garbage collection callback, showing basic lifecycle management and explicit cleanup.
Design your application with robust fallback mechanisms for resource cleanup, such as explicit `dispose()` methods or other lifecycle hooks, rather than solely depending on GC for critical tasks.
If direct access to the original object or a custom wrapper is needed without proxy behavior, use the `return` option in `create(value, callback, { return: customWrapper })`.Carefully review cleanup callbacks to ensure they only use the provided `heldValue` argument and do not close over or retain strong references to the original `target` or its related state after it's meant to be unreachable. `gc-hook`'s design helps, but developer vigilance is still required.
Understand and communicate that `FinalizationRegistry` is for 'best-effort' cleanup, not guaranteed resource release. For critical resources, implement explicit `close()` or `dispose()` methods. To observe GC activity more reliably in development, try running with `--expose-gc` flag in Node.js and manually calling `global.gc()`.
Thoroughly inspect all code paths for strong references. Use a memory profiler (e.g., Chrome DevTools heap snapshot) to identify what is still holding onto the object. Ensure the `onGarbageCollected` callback does not create new strong references to the object it's meant to clean up. If using `gc-hook/track`, remember it uses `console.debug`, which might have its own retention behavior in some environments.
If you need to interact with the raw object or a specific wrapper, consider using the `return` option in `create`. For example, `create(ref, onGC, { return: ref })` would return the `ref` itself, though this negates the strong reference protection `gc-hook` provides and should only be done if you are sure about managing references externally.No dependency data recorded yet.