'Repeat Fetching with UseEffect and SetTimeOut on React.js

I want to make Component that Fetching Data from REST API with repeatedly.

I noticed There is some problem with setInterval and React.js.

so I coded recursive way with setTimeout and useEffect.

It seems work well though, I am curious about necessity of clearTimeout.

Is there no performance Issue cause of no clearTimeout or else?

ps: Sorry for my poor English.

import { useEffect, useState } from "react";
import axios from "axios";

function RepeatFetch() {
  const [data, setData] = useState(null);
  const repeatFetchData = async () => {
    try {
      const response = await axios.get(
        "https://api.foo.com/"
      );
      setData(response.data);
    } catch (e) {
    }
    setTimeout(repeatFetchData, 3000);
  };

  useEffect(() => {
    responseFetchData();
    // return () => clearTimeout(timer); // Do I need clearTimeout? then, how?
  }, []);

  return (
    <div>
      {data}
    </div>
  );
}

export default RepeatFetch;



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source