0

Can somebody spot the bug, UI is not rendering, I tried by passing formatTime as a dependency to the useEffect but it is behaving very annoyingly.

Observation: It's inconsistent sometimes it works on page reload but sometimes it don't rerender the view

import React, { useState, useEffect, useCallback } from "react";
import "./styles.css";

export default function App() {
  let date = new Date();

  const formatTime = useCallback(() => {
    return (
      date.getHours().toString() +
      ":" +
      date.getMinutes().toString() +
      ":" +
      date.getSeconds().toString() +
      ":" +
      date.getMilliseconds().toString()
    );
  }, [date]);

  const [timer, setTimer] = useState(formatTime());

  useEffect(() => {
    let interval = setInterval(() => {
      setTimer(formatTime());
    });
    return () => {
      clearInterval(interval);
    };
  });

  return (
    <div className="App">
      <h3> Timer: {timer.toString()} </h3>
    </div>
  );
}
Abhin Pai
  • 332
  • 3
  • 10
  • Are you intentionally not passing a delay in milliseconds to `setInterval`? – cbr Jul 23 '20 at 19:41
  • Yes, I left as is to check the UI updates – Abhin Pai Jul 23 '20 at 19:48
  • Date is updating and setting the state via `formatTime()` in `useEffect`. Anyways I found a solution for it. Thank you @cbr https://codesandbox.io/s/debounce-throttling-loqvg?file=/src/App.js:540-564 – Abhin Pai Jul 23 '20 at 20:05

0 Answers0