watchEffect
Overview
Section titled “Overview”The watchEffect
function allows you to create an “effect” that automatically reacts to changes in reactive data, such as ref objects or other observables. This effect is useful for handling side effects, such as updating the UI, in a reactive and efficient manner.
Creating Effects
Section titled “Creating Effects”To create an effect using watchEffect
, you provide a function that defines the effect. This function will be called immediately and then re-called whenever the reactive data it depends on changes.
import { watchEffect, ref } from 'regor'
const myRef = ref('Hello, Regor!')
// Create a watch effectconst stopWatching = watchEffect(() => { console.log('Value:', myRef.value)})
// Later, when the effect is no longer needed, stop itstopWatching()
Parameters
Section titled “Parameters”effect
: A function that defines the effect you want to create. This function may optionally receive a callback function (onCleanup
) as an argument.
Return Value
Section titled “Return Value”- The
watchEffect
function returns astopWatching
function that allows you to stop the effect when it’s no longer needed. CallingstopWatching
will unsubscribe the effect from the reactive data.
Example
Section titled “Example”import { watchEffect, ref } from 'regor'
const myRef = ref('Hello, Regor!')
// Create a watch effect that updates the UIconst stopWatching = watchEffect(() => { console.log('Value:', myRef.value)})
// Later, when the effect is no longer needed, stop itstopWatching()