useMemoizedMetricField
This hook is very similar to the useMetricField
hook, which the difference, that you can pass
a memo
function to it which should return a derived value from the ChannelValue
.
If a new value comes in from polling the metric and the value returned by the memo
function did not change, no
re-render will be triggered.
This is especially helpful for widgets that work for example with numeric metrics and only use a smaller precision of the metric value. This way the widget does not need to re-render if the value only changes in a precision, which is not even shown to the user.
Arguments
The hook can take an object as argument with the following properties.
Field | Type | Description |
---|---|---|
field | string | The name of the field |
memo | (value: ChannelValue | null) => T | null | The memo function to compare the values. Should be a callback that's not re-created on every render. |
equals | (oldValue: T | null, newValue: T | null) => boolean | An optional equals function on how the values returned by memo should be compared. Defaults to lodash's isEqual function |
Returns
An object with the following properties.
Field | Type | Description |
---|---|---|
value | T | The derived value returned by the given memo function |
channelValue | ChannelValue | The channel value for the metric |
Example
src/widgets/example/Example.tsx
import React, {useCallback} from 'react'
import {useMemoizedMetricField, ChannelValue} from '@modbros/dashboard-sdk'
export default function Example() {
const memo = useCallback((channelValue: ChannelValue) => {
return Math.round(parseFloat(channelValue.value?.value?.toString()))
}, [])
const {value, channelValue} = useMemoizedMetricField({
field: 'example',
memo
})
return null
}