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
Type | Description | |
---|---|---|
id? | string | An optional |
returns | Metrics | 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 an 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.
const App = ({metrics}) => (
<Provider metrics={metrics}>
<Pane />
</Provider>
);
const Pane = () => <span>{useMetrics().getListenerStats().metric}</span>;
const metrics = createMetrics(createStore());
const app = document.createElement('div');
ReactDOM.render(<App metrics={metrics} />, app);
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.
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');
ReactDOM.render(<App metrics={metrics} />, app);
console.log(app.innerHTML);
// -> '<span>0</span>'