简体   繁体   中英

Infinite loop useEffect() hook

So, I am using hook useState():

const [dailyData, setDailyData] = useState({});

And useEffect() hook to fetch data from API:

 useEffect(() => {
    const fetchAPI = async () => {
        setDailyData(await fetchDailyData())
    }

    console.log(dailyData)

    fetchAPI();
});

But the problem is that these requests are endless.

I'm new in React, so it would be great if you'd explain why this is caused.

Your useEffect is triggered when any state data is updated.

So if you update dailyData inside your useEffect , the state change will trigger useEffect again.

You can add a dependency array to useEffect or any flag variable for proper actions.

For example, adding an empty dependency array will work like componentDidMount .

useEffect(() => {
    // Do something here
}, []);

Your useEffect needs an array dependency ex.

useEffect(() => {
 const fetchAPI = async () => {
    setDailyData(await fetchDailyData())
 }

 console.log(dailyData)

 fetchAPI();
}, []);

To make useEffect to run only one time you have to give an empty array in useEffect function

useEffect(() => {
    const fetchAPI = async () => {
        setDailyData(await fetchDailyData())
    }

    console.log(dailyData)

    fetchAPI();
},[]);

If you want to run useEffect when some change occur you can specify the value in the array and whenever there will be any change in the variable the useEffect will run again.

Each time state of variable in component is changed useEffect() hook will run. So to avoid infinite loop you need to nest dependency array in useEffect() hook.

Your code can be modified as

 const [dailyData, setDailyData] = useState({});

     useEffect(() => {
     const fetchAPI = async () => {
        setDailyData(await fetchDailyData())
      }

        console.log(dailyData)

     fetchAPI();
   },  [ //dependency array]);
 

Dependency array can be defined as it is the second optional argument in the useEffect function. As the name implies, it is an array of dependencies that, when changed from the previous render, will recall the effect function defined in the first argument.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM