gc-hook: Simplified FinalizationRegistry

0.4.1 · maintenance · verified Sun Apr 19

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.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to use `create` to register an object with a garbage collection callback, showing basic lifecycle management and explicit cleanup.

import { create, drop } from 'gc-hook';

// Keep a count of all passed references created here
let references = 0;

// Notify how many references are still around once collected
const onGarbageCollected = myUtility => {
  console.log(--references, 'references still used');
};

const createUtility = options => {
  const myUtility = { ...options, do: 'something' };
  console.log(++references, 'references provided');
  // Return a proxy to avoid holding directly myUtility,
  // while keeping the utility in memory until such proxy
  // is not needed, used, or referenced anymore.
  return create(myUtility, onGarbageCollected);
};

// As a module consumer:
let util = createUtility({ some: 'thing' });
console.log('Utility created:', util);

// Do something amazing with the util...

// Simulate releasing the utility after some time
setTimeout(() => {
  // Clear the utility or don't reference it anymore anywhere
  util = null;
  console.log('Utility reference cleared. Awaiting GC...');
  // Once the GC kicks in, the module.js will log how many
  // utilities are still around and never collected.
  // Note: GC is non-deterministic, so the log might not appear immediately.
}, 100);

view raw JSON →