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
Type | Description | |
---|---|---|
metricId | IdOrNull | |
listener | MetricListener | The function that will be called whenever the |
listenerDeps? | DependencyList | An optional array of dependencies for the |
metricsOrMetricsId? | MetricsOrMetricsId | The |
returns | void | 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.
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.
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 = ReactDOMClient.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