onCleanup
Edit this pageonCleanup registers a cleanup function on the current reactive scope.
The cleanup runs when that scope is disposed or refreshed.
Import
import { onCleanup } from "solid-js";Type
function onCleanup<T extends () => any>(fn: T): T;Parameters
fn
- Type:
() => any - Required: Yes
Cleanup function registered on the current reactive scope.
Return value
- Type:
T
Returns fn unchanged.
Behavior
- In a component, the cleanup runs when that component is unmounted.
- In a tracking scope such as
createEffect,createMemo, orcreateRoot, the cleanup runs when that scope is disposed or re-executes. - Multiple cleanup functions run when the owning scope is cleaned up.
- Calling
onCleanupoutside a reactive owner does not register a cleanup. In development, Solid warns that the cleanup will never run. - On the server, cleanup also runs when server-side owners or reactive branches are disposed.
Examples
Remove an event listener
import { onCleanup } from "solid-js";
const Component = () => { const handleClick = () => console.log("clicked");
document.addEventListener("click", handleClick);
onCleanup(() => { document.removeEventListener("click", handleClick); });
return <main>Listening for document clicks</main>;};Clean up before an effect re-runs
import { createEffect, createSignal, onCleanup } from "solid-js";
function Example() { const [topic, setTopic] = createSignal("news");
createEffect(() => { const currentTopic = topic();
console.log("subscribing to", currentTopic);
onCleanup(() => { console.log("cleaning up", currentTopic); }); });
return <button onClick={() => setTopic("sports")}>Change topic</button>;}