Skip to main content

Watching For State Changes

We can create a watcher to observe state changes with the .watch method.

It accepts a callback function as its parameter and it will be invoked whenever the state changes.

The .watch method returns a callback, that when called, will remove the watcher.

Example

In the example below, we have an interval that sets the CounterState with random numbers every second.

A watcher is added to observe these changes and it will push the state values into an array. Once the array has 10 numbers, the unwatch function is called to stop watching.