TinyBase logoTinyBase β

useMetricListener

The useMetricListener hook registers a listener function with the Metrics object that will be called whenever the value of a specified Metric changes.

useMetricListener(
  metricId: IdOrNull,
  listener: MetricListener,
  listenerDeps?: DependencyList,
  metricsOrMetricsId?: MetricsOrMetricsId,
): void
TypeDescription
metricIdIdOrNull

The Id of the Metric to listen to, or null as a wildcard.

listenerMetricListener

The function that will be called whenever the Metric changes.

listenerDeps?DependencyList

An optional array of dependencies for the listener function, which, if any change, result in the re-registration of the listener. This parameter defaults to an empty array.

metricsOrMetricsId?MetricsOrMetricsId

The Metrics object to register the listener with: omit for the default context Metrics object, provide an Id for a named context Metrics object, or provide an explicit reference.

returnsvoid

This has no return value.

This hook is useful for situations where a component needs to register its own specific listener to do more than simply tracking the value (which is more easily done with the useMetric hook).

You can either listen to a single Metric (by specifying the Metric Id as the method's first parameter), or changes to any Metric (by providing a null wildcard).

Unlike the addMetricListener method, which returns a listener Id and requires you to remove it manually, the useMetricListener hook manages this lifecycle for you: when the listener changes (per its listenerDeps dependencies) or the component unmounts, the listener on the underlying Metrics object, will be deleted.

Example

This example uses the useMetricListener hook to create a listener that is scoped to a single component. When the component is unmounted, the listener is removed from the Metrics object.

import {Provider, useMetricListener} from 'tinybase/ui-react';
import {createMetrics, createStore} from 'tinybase';
import React from 'react';
import {createRoot} from 'react-dom/client';

const App = ({metrics}) => (
  <Provider metrics={metrics}>
    <Pane />
  </Provider>
);
const Pane = () => {
  useMetricListener('highestPrice', () => console.log('Metric changed'));
  return <span>App</span>;
};

const store = createStore().setTable('species', {
  dog: {price: 5},
  cat: {price: 4},
  worm: {price: 1},
});
const metrics = createMetrics(store);
metrics.setMetricDefinition('highestPrice', 'species', 'max', 'price');

const app = document.createElement('div');
const root = createRoot(app);
root.render(<App metrics={metrics} />);
console.log(metrics.getListenerStats().metric);
// -> 1

store.setCell('species', 'horse', 'price', 20);
// -> 'Metric changed'

root.unmount();
console.log(metrics.getListenerStats().metric);
// -> 0

Since

v1.0.0