DocsBlog
  • 1.3.0

  • light

    dark

    system

    Switch mode
  • Cerberus

    Acheron

    Elysium

Get Started
Components
Data Grid
Signals
Styling
Theming

Get Started

OverviewReactivityData FetchingStores

Primitives

createSignalcreateQueryNewcreateMutationNewcreateComputedcreateEffectcreateStoreContextbatchonCleanupNewuntrackNew

Hooks

useQueryNewuseMutationuseReaduseSignaluseStoreNew

Components

ReactiveText

On this page

Loading...

Loading...

Loading...

Loading...

Cleanup Effects

Learn how to register cleanup functions to effects.

  • source
import { onCleanup } from '@cerberus/signals'

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:

  1. createEffect
  2. createComputed

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.

  1. DOM Subscriptions: Removing window or document event listeners when the dependencies change.
  2. Timer Management: Clearing setTimeout or setInterval cycles.
  3. Network Cancellation: Triggering an AbortController to cancel stale network requests if a user rapidly clicks a button.
  4. 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.

import { createEffect, onCleanup } from '@cerberus/signals'

createEffect(() => {
  const timer = setInterval(() => console.log('Tick'), 1000)
  onCleanup(() => clearInterval(timer))
})

On this page

  • Usage
  • When to use
  • API
  • Edit this page on Github