watch

Signature
watch<T>(atom: Atom<T>): { value: T, set: SetterFn<T>, reset: () => void }

valdres-svelte Subscribe to and update an atom's value

Returns a reactive object with the current value, a setter, and a reset function. In Svelte 5, the .value property is reactive and triggers re-renders automatically.

Usage

<script>
import { atom } from "valdres"
import { watch } from "valdres-svelte"

const countAtom = atom(0)
const count = watch(countAtom)
</script>

<div>
    <span>{count.value}</span>
    <button onclick={() => count.set(c => c + 1)}>+</button>
    <button onclick={() => count.reset()}>Reset</button>
</div>

With selectors

When watching a selector, the returned object is read-only (no set or reset):

<script>
import { atom, selector } from "valdres"
import { watch } from "valdres-svelte"

const nameAtom = atom("Valdres")
const greeting = watch(selector(get => `Hello, ${get(nameAtom)}!`))
</script>

<h1>{greeting.value}</h1>

See also