UseEffect being called multiple times UseEffect being called multiple times reactjs reactjs

UseEffect being called multiple times


Your useEffect is executed only once per render cycle, but you have several state updates in your useEffect which cause a re-render. Hence you get a lot of alerts.

See a demo of your code and see the console.logs as well as comments

Also note that useEffect will

  • when you provide empty array dependency, your useEffect execute once
  • when you some value as dependency (eg: [name] ), your useEffect execute when name state/prop changes
  • useEffect executes on every re-render if you don't provide any dependency.

Read here on re-render


refactor it like this.

import React, { useEffect, useState } from "react";//import "./App.css";const DemoFetchZ = () => {  const [todo, setTodo] = useState({});  const [loading, setLoading] = useState(false);  useEffect(() => {    fetchData();  }, []);  const fetchData = () => {    setLoading(true);    fetch("https://jsonplaceholder.typicode.com/todos/1")      .then((response) => response.json())      .then((data) => {        setTodo(data);        setLoading(false);      })      .catch((error) => {        console.log(error);        setLoading(false);      });  };  return (    <>      {loading ? (        <div>...Data Loading.....</div>      ) : (        <div>          - Fetch          <br />          <span>Title: {todo ? todo.title : "no Title Found"}</span>        </div>      )}    </>  );};export default DemoFetchZ;