0

I am new to react so really sorry if this question has already been asked.

I am fetching data from an API in an useEffect hook and I only want to fetch it once but instead its being fetched twice for some reason.

Here's the code of useEffect hook

useEffect(() => {
    const fetchTasks = async () => {
      const res = await fetch('http://localhost:8080/tasks')
      const data = await res.json()
      console.log(data)
      for (let i = 0; i < data.length; i++) {
        setNewTaskContent(newTaskContent => [...newTaskContent, <Task task={data[i]} />])
      }
    }
    fetchTasks()
  }, [])

This was supposed to run once when the page was loaded but I am getting an array of data twice.

And if I am removing the dependency array from the hook, its fetching data continuously in a loop.

1 Answers1

2

In strict mode, React will render every component twice during development. To prevent getting duplicate data, you should return a cleanup function from useEffect that ignores the current request. (Do not disable strict mode unless you have a very good reason to.)

useEffect(() => {
    let ignore = false;
    const fetchTasks = async () => {
      const res = await fetch('http://localhost:8080/tasks')
      const data = await res.json();
      if (ignore) return;
      for (let i = 0; i < data.length; i++) {
        setNewTaskContent(newTaskContent => [...newTaskContent, <Task task={data[i]}/>])
      }
    }
    fetchTasks();
    return () => ignore = true;
}, []);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80