createRoot
Creates an ownership scope.
Creates an ownership scope. Everything created inside (effects, memos, cleanups, children) is
disposed together when dispose is called or, for attached roots, when the parent disposes. Use
it for code that runs outside a component, such as an app entry point, a test or a module that
owns long-lived effects.
Import#
ts
import { createRoot } from "@shadow-js/core";
Signature#
ts
function createRoot<T>(fn: (dispose: () => void) => T, options?: RootOptions): T
Parameters#
| Name | Description |
|---|---|
fn |
Body; receives the dispose function. Runs untracked, with the new root as owner. |
options |
detached keeps the root out of the current owner. Undefined uses the default (attached). |
Returns#
Whatever fn returns.
Throws#
- Rethrows any error thrown by
fn, after the root and everything created in it are disposed.
Examples#
ts
import { createRoot, useEffect, useSignal } from "@shadow-js/core";
const [count, setCount] = useSignal(0);
const dispose = createRoot((dispose) => {
useEffect(() => console.log(count()));
return dispose;
});
setCount(1);
dispose(); // the effect stops and its cleanups run