0

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;

reaver lover
  • 448
  • 4
  • 16
  • 2
    _"Do I need clearTimeout?"_ - It won't break your app but you should clear the timeout. What happens if the timer is set but _before_ it fires, your component is unmounted? In that case, you will send the request – Yousaf Jan 27 '22 at 08:01

0 Answers0