Home > @pago/reactive > watchEffect

watchEffect() function

Executes the given effect immediately and tracks any used values. When any of them change, it will execute the effect again. If a teardown function has been registered through the onInvalidate param, it will be executed before the effect is executed again, allowing for cleanup.

Signature:

export declare function watchEffect(fn: (onInvalidate: (teardown: Effect) => void) => void): Effect;

Parameters

Parameter Type Description
fn (onInvalidate: (teardown: Effect) => void) => void The effect that should be executed when any of the tracked values change.

Returns:

Effect

Remarks

When using this function within a Reactive Component, make sure to not rely on any custom teardown logic.

When this function is used within a Reactive Component, the tracking will be bound to the components lifecycle. It is, therefore, save to use and can be considered side effect free (and thus React Concurrent Mode compatible). However, there are circumstances that might cause a custom teardown function to not be invoked.

For example, if your component has been rendered but not committed (written to the DOM) then React reserves the right to throw it away without invoking any cleanup logic.

// DO NOT DO THIS
import { watchEffect, ref } from '@pago/reactive';
function Surprise(props) {
 const message = ref('Wait for it...');
 watchEffect(onInvalidate => {
   // This timer will never be cleared
   // if the component is not unmounted
   // or during server side rendering
   // You should use `effect` instead
   const token = setTimeout(() => {
     message.current = 'Hello World!'
   }, props.delay); // props.delay is watched
   onInvalidate(() => clearTimeout(token));
 });
 return () => <p>{message.current}</p>
}