Reactive Utilities

on

Edit this page
import { on } from "solid-js"
function on<T extends Array<() => any> | (() => any), U>(
deps: T,
fn: (input: T, prevInput: T, prevValue?: U) => U,
options: { defer?: boolean } = {}
): (prevValue?: U) => U | undefined

on is designed to be passed into a computation to make its dependencies explicit. If an array of dependencies is passed, input and prevInput are arrays.

createEffect(on(a, (v) => console.log(v, b())));
// is equivalent to:
createEffect(() => {
const v = a();
untrack(() => console.log(v, b()));
});

You can also not run the computation immediately and instead opt in for it to only run on change by setting the defer option to true.

// doesn't run immediately
createEffect(on(a, (v) => console.log(v), { defer: true }));
setA("new"); // now it runs

Using on with stores

const [state, setState] = createStore({ a: 1, b: 2 });
// this will not work
createEffect(on(state.a, (v) => console.log(v)));
setState({ a: 3 }); // logs nothing
// instead, use an arrow function
createEffect(
on(
() => state.a,
(v) => console.log(v)
)
);
setState({ a: 4 }); // logs 4

Arguments and options

ArgumentTypeDescription
depsTThe dependencies to watch.
fn(input: T, prevInput: T, prevValue?: U) => UThe function to run when the dependencies change.
options{ defer?: boolean }Options to configure the effect.
Report an issue with this page