{
  "id": "70a26f18718fd510e5e54215",
  "source": "solid:signals",
  "type": "github-document",
  "title": "on-cleanup",
  "content": "---\ntitle: onCleanup\norder: 5\nuse_cases: \u003e-\n  component unmounting, memory leak prevention, event listener cleanup, side\n  effect cleanup, resource disposal\ntags:\n  - lifecycle\n  - cleanup\n  - memory\n  - events\n  - disposal\nversion: '1.0'\ndescription: \u003e-\n  Register cleanup methods in SolidJS to prevent memory leaks. Executes when\n  components unmount or tracking scopes dispose. Essential for proper cleanup.\n---\n\n`onCleanup` registers a cleanup method that executes on disposal and recalculation of the current tracking scope.\nCan be used anywhere to clean up any side effects left behind by initialization.\n\nWhen used in a Component, it runs when the component is unmounted.\nWhen used in tracking scope, such [`createEffect`](/reference/basic-reactivity/create-effect), [`createMemo`](/reference/basic-reactivity/create-memo) or a [`createRoot`](/reference/reactive-utilities/create-root), it runs when the tracking scope is disposed or refreshed.\n\n```ts\nimport { onCleanup } from \"solid-js\"\n\nfunction onCleanup(fn: () =\u003e void): void;\n```\n\nWithout the `onCleanup` function, the event listener would remain attached to the `document` even after the component is removed from the page.\nThis can cause memory leaks and other issues.\n\n```tsx\nimport { createSignal, onCleanup } from \"solid-js\"\n\nconst Component = () =\u003e {\n\tconst [count, setCount] = createSignal(0);\n\n\tconst handleClick = () =\u003e setCount((value) =\u003e value + 1);\n\n\tdocument.addEventListener(\"click\", handleClick);\n\n\t/**\n\t * Remove the event listener when the component is removed/unmounted from the page.\n\t */\n\tonCleanup(() =\u003e {\n\t\tdocument.removeEventListener(\"click\", handleClick);\n\t});\n\n\treturn \u003cmain\u003eDocument has been clicked {count()} times\u003c/main\u003e;\n};\n```",
  "url": "https://github.com/solidjs/solid-docs/blob/HEAD/src/routes/reference/lifecycle/on-cleanup.mdx",
  "metadata": {
    "path": "src/routes/reference/lifecycle/on-cleanup.mdx",
    "repo": "solidjs/solid-docs",
    "repo_url": "https://github.com/solidjs/solid-docs.git",
    "size": 1721,
    "source_type": "github"
  },
  "hash": "960df19d7bd6ea0f1c89ec0d22f326f49092539122cc8a57eee1b6773e26c517",
  "timestamp": "2026-02-23T11:43:00.189693828+01:00"
}