useChangeObserver

Source
import { useChangeObserver } from "@prestojs/util";
useChangeObserver<T>(value,onChange,?options)
Source

Call a function whenever a value changes.

This works by monitoring a value passed in and tracking it's last value. Whenever the value changes the provided callback will be called with the last and current value.

export default function Example() {
  const [count, setCount] = useState(0);
  useChangeObserver(count, () => {
    console.log(`Changed from ${prev} to ${next}.`));
  }
  return <>
    Count: {count}
    <button onClick={() => setCount(c => c+1)}>+1</button>
  </>;
}

For more advanced monitoring of lists of values see useListChangeObserver.

Arguments:

ArgumentTypeDescription
*valueT

The value to monitor for changes. This can be any type but for complex types you will need to provide your own isEqual function. For simple shallow comparisons the default function will suffice (eg. it will compare each element in an array or each value on an object 1 level deep).

*onChange

The function to call when value changes. This is passed the previous value and the current value.

options
An object with the properties below
options.disabledboolean

If true then no changes will be detected. When this changes from true to false the callback won't be called until the next change in value. This is useful for disabling the callback when no value is yet available eg. when waiting for first response from an API.

options.isEqual

Function to determine equality between items. If not provided the default will do shallow equality checks with specific support for an isEqual function on objects (eg. if an object implements isEqual it will be called instead of doing any other comparisons. This is supported by ViewModel).

Returns:void

Has no return value

Examples

Notify when a value changes