Usage
The onCleanup primitive is an essential memory-management tool within the Cerberus Signals reactivity system. It allows you to register a callback function that will execute right before a reactive context (like createEffect or createComputed) re-evaluates, or when that context is permanently destroyed.
This is the signal-based equivalent of returning a cleanup function in React's useEffect, but with significantly more flexibility.
onCleanup works within the scope of either:
In this example, we ensure a timer is cleared when it's parent effect is destroyed.
When to use
Whenever an effect re-runs, any side effects from its previous run (like event listeners, intervals, or network requests) must be disposed of, or your application will suffer from severe memory leaks and race conditions.
Unlike React, where you must return a single cleanup function at the very end of your hook, onCleanup can be called anywhere inside your reactive scope, even deeply nested inside helper functions.
- DOM Subscriptions: Removing
windowordocumentevent listeners when the dependencies change. - Timer Management: Clearing
setTimeoutorsetIntervalcycles. - Network Cancellation: Triggering an
AbortControllerto cancel stale network requests if a user rapidly clicks a button. - Composable Helpers: Building custom reactive utilities that manage their own memory cleanup without forcing the consumer to manually handle it.
API
onCleanup accepts a callback function and operates functionally the same at createEffect and createComputed.