Я бы рекомендовал избегать установки состояния каждые 1 мс, и вместо этого вы можете упростить пример часов, используя moment (или moment-timezone ) и простой пользовательский хук:
Рабочий пример:
index.js
import React, { Fragment } from "react";
import { render } from "react-dom";
import { Container, CurrentDate, DisplayTime, Title } from "./components";
import { useTimer } from "./hooks";
const timezone = "Europe/Oslo";
const timeformat = "HH:mm:ss";
const dateformat = "DD.MMMM.YYYY";
const Clock = () => {
const { currentDate, currentTime } = useTimer(
timezone,
timeformat,
dateformat
);
return (
<Fragment>
<Title>Simple Clock Example</Title>
<Container>
<CurrentDate>{currentDate}</CurrentDate>
<DisplayTime>{currentTime}</DisplayTime>
</Container>
</Fragment>
);
};
render(<Clock />, document.getElementById("root"));
hooks / useTimer / index.js
import PropTypes from "prop-types";
import moment from "moment-timezone";
import { useCallback, useEffect, useRef, useState } from "react";
const useTimer = (timezone, timeformat, dateformat) => {
// reuseable function to return current time
const getCurrentTime = useCallback(
format =>
moment()
.tz(timezone)
.format(format),
[timezone]
);
// utilize a ref to set and clear an interval
const intervalRef = useRef();
// utilize state to initialize and update "currentTime"
const [currentTime, setTime] = useState(getCurrentTime(timeformat));
// create a 1000ms setInterval timer to update "currentTime".
const startTimer = useCallback(() => {
intervalRef.current = setInterval(() => {
setTime(getCurrentTime(timeformat));
}, 1000);
}, [getCurrentTime, intervalRef, timeformat]);
// during initial load start the timer
// during unmount remove the interval
useEffect(() => {
if (!intervalRef.current) {
startTimer();
}
return () => {
if (intervalRef.current) {
clearInterval(intervalRef.current);
intervalRef.current = undefined;
}
};
}, [intervalRef, startTimer]);
return {
currentDate: getCurrentTime(dateformat),
currentTime
};
};
useTimer.propTypes = {
dateformat: PropTypes.string.isRequired,
format: PropTypes.string.isRequired,
timezone: PropTypes.string.isRequired
};
export default useTimer;