TinyBase logoTinyBase β

useMetrics

The useMetrics hook is used to get a reference to a Metrics object from within a Provider component context.

useMetrics(id?: string): Metrics | undefined
TypeDescription
id?string

An optional Id for accessing a Metrics object that was named with an Id in the Provider.

returnsMetrics | undefined

A reference to the Metrics object (or undefined if not within a Provider context, or if the requested Metrics object does not exist).

A Provider component is used to wrap part of an application in a context. It can contain a default Metrics object (or a set of Metrics objects named by Id) that can be easily accessed without having to be passed down as props through every component.

The useMetrics hook lets you either get a reference to the default Metrics object (when called without a parameter), or one of the Metrics objects that are named by Id (when called with an Id parameter).

Examples

This example creates a Provider context into which a default Metrics object is provided. A component within it then uses the useMetrics hook to get a reference to the Metrics object again, without the need to have it passed as a prop.

import {Provider, useMetrics} 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 = () => <span>{useMetrics().getListenerStats().metric}</span>;

const metrics = createMetrics(createStore());
const app = document.createElement('div');
createRoot(app).render(<App metrics={metrics} />);
console.log(app.innerHTML);
// -> '<span>0</span>'

This example creates a Provider context into which a Metrics object is provided, named by Id. A component within it then uses the useMetrics hook with that Id to get a reference to the Metrics object again, without the need to have it passed as a prop.

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

const App = ({metrics}) => (
  <Provider metricsById={{petStore: metrics}}>
    <Pane />
  </Provider>
);
const Pane = () => (
  <span>{useMetrics('petStore').getListenerStats().metric}</span>
);

const metrics = createMetrics(createStore());
const app = document.createElement('div');
createRoot(app).render(<App metrics={metrics} />);
console.log(app.innerHTML);
// -> '<span>0</span>'

Since

v1.0.0