From 9fe5133ef1f0a9b29a9d40db28e97be649462b4a Mon Sep 17 00:00:00 2001 From: Thomas Nordquist Date: Sun, 16 Jun 2019 20:55:55 +0200 Subject: [PATCH] Improve plot performance with memoization --- app/src/components/Sidebar/PlotHistory.tsx | 61 ++++++++-------------- 1 file changed, 23 insertions(+), 38 deletions(-) diff --git a/app/src/components/Sidebar/PlotHistory.tsx b/app/src/components/Sidebar/PlotHistory.tsx index 702251c..99ea753 100644 --- a/app/src/components/Sidebar/PlotHistory.tsx +++ b/app/src/components/Sidebar/PlotHistory.tsx @@ -1,8 +1,7 @@ import * as React from 'react' import DateFormatter from '../helper/DateFormatter' import { default as ReactResizeDetector } from 'react-resize-detector' -import { Theme } from '@material-ui/core' -import { withTheme } from '@material-ui/styles' +import { Theme, withTheme } from '@material-ui/core' import 'react-vis/dist/style.css' const { XYPlot, LineMarkSeries, Hint, XAxis, YAxis, HorizontalGridLines } = require('react-vis') const abbreviate = require('number-abbreviate') @@ -12,61 +11,47 @@ interface Props { theme: Theme } -interface Stats { - width: number - value?: any -} +export default withTheme((props: Props) => { + const [width, setWidth] = React.useState(300) + const [tooltip, setTooltip] = React.useState({ value: undefined }) + const detectResize = React.useCallback(width => setWidth(width), []) -class PlotHistory extends React.Component { - constructor(props: Props) { - super(props) - this.state = { width: 300 } - } - - private resize = (width: number, height: number) => { - this.setState({ width: width - 12 }) - } - - private hintFormatter = (point: any) => { + const hintFormatter = React.useCallback((point: any) => { return [ { title: Time, value: }, { title: Value, value: point.y }, ] - } + }, []) - private _forgetValue = () => { - this.setState({ - value: undefined, - }) - } + const hideTooltip = React.useCallback(() => { + setTooltip({ value: undefined }) + }, []) - private _rememberValue = (value: any) => { - this.setState({ value }) - } + const showTooltip = React.useCallback((value: any) => { + setTooltip({ value }) + }, []) - public render() { - const data = this.props.data + const data = props.data + return React.useMemo(() => { return (
- + abbreviate(num)} /> - {this.state.value ? : null} + {tooltip.value ? : null} - +
) - } -} - -export default withTheme(PlotHistory) + }, [width, data, tooltip]) +})