DateTime: avoid unnecessary update #6110

Merged
infinite-persistence merged 1 commit from ip/date.time.optimization into master 2021-05-25 00:29:58 +02:00

View file

@ -2,15 +2,29 @@
import React from 'react';
import moment from 'moment';
const DEFAULT_MIN_UPDATE_DELTA_MS = 60 * 1000;
type Props = {
date?: any,
timeAgo?: boolean,
formatOptions: {},
formatOptions?: {},
show?: string,
clock24h: boolean,
clock24h?: boolean,
minUpdateDeltaMs?: number,
};
class DateTime extends React.PureComponent<Props> {
type State = {
lastRenderTime: Date,
};
class DateTime extends React.Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = {
lastRenderTime: new Date(),
};
}
static SHOW_DATE = 'date';
static SHOW_TIME = 'time';
@ -45,6 +59,38 @@ class DateTime extends React.PureComponent<Props> {
return __(strId, { duration });
}
shouldComponentUpdate(nextProps: Props): boolean {
if (
moment(this.props.date).diff(moment(nextProps.date)) !== 0 ||
this.props.clock24h !== nextProps.clock24h ||
this.props.timeAgo !== nextProps.timeAgo ||
this.props.minUpdateDeltaMs !== nextProps.minUpdateDeltaMs ||
this.props.show !== nextProps.show
) {
return true;
}
if (this.props.timeAgo && nextProps.timeAgo) {
const minUpdateDeltaMs = this.props.minUpdateDeltaMs || DEFAULT_MIN_UPDATE_DELTA_MS;
const prev = moment(this.state.lastRenderTime);
const curr = moment(new Date());
const deltaMs = curr.diff(prev);
if (deltaMs > minUpdateDeltaMs) {
return true;
}
}
return false;
}
componentDidUpdate() {
const { timeAgo } = this.props;
if (timeAgo) {
this.setState({ lastRenderTime: new Date() });
}
}
render() {
const { date, timeAgo, show, clock24h } = this.props;