Home > Blockchain >  React app Clock having an error in useEffect
React app Clock having an error in useEffect

Time:08-12

Just a newbie question I wonder what should I do to make work the useEffect I am getting error on the useEffect

Line 15:6: React Hook useEffect has a missing dependency: 'refreshClock'. Either include it or remove the dependency array react-hooks/exhaustive-deps

import  { useState, useEffect } from "react";

function App() {
  const { time, setTime } = useState(new Date());

  function refreshClock() {
    setTime(new Date());
  }

  useEffect(() => {
    const timerID = setInterval(refreshClock, 1000);
    return function cleanup() {
      clearInterval(timerID);
    };
  }, []);

  return <span>Time : {time.toLocaleTimeString()}</span>;
}

export default App;

CodePudding user response:

The warning is due to the fact that you make use of refreshClock function inside useEffect() without declaring it in the dependency array.

Additionally you would get another warning regarding setTime, here you can make use of useCallback() and declare setTime inside its own dependency array.

function App() {
  const [time, setTime] = useState(new Date());

  const refreshClock = React.useCallback(() => {
    setTime(new Date());
  }, [setTime]);

  useEffect(() => {
    const timerID = setInterval(refreshClock, 1000);
    return function cleanup() {
      clearInterval(timerID);
    };
  }, [refreshClock]);

  return <span>Time : {time.toLocaleTimeString()}</span>;
}

CodePudding user response:

The issue about missing dependencies in useEffect() is just a warning and not the the main reason why the above code doesn't work. Actually the useState() has not been destructured correctly. You need to destrucuture into an array (please notice the [] instead of {} on useState() line):

import { useState, useEffect } from "react";

function App() {
  const [time, setTime] = useState(new Date());

  useEffect(() => {
    function refreshClock() {
      setTime(new Date());
    }
    const timerID = setInterval(refreshClock, 1000);
    return function cleanup() {
      clearInterval(timerID);
    };
  }, [setTime]);

  return <span>Time : {time.toLocaleTimeString()}</span>;
}

export default App;

Sandbox

This is because useState() returns an array. {} notation is used to destructure an object.

As a side note it is a good idea to include the function within useEffect as shown above. Please read more about it here: https://reacttraining.com/blog/when-to-use-functions-in-hooks-dependency-array/

  • Related