useEffect.dev
← Back to lessons

Lesson 7. Solving infinite loops when using useEffect 1. No dependencies array

The first cause of infinite loops is the easiest to identify and fix:

Result

In this code, the intention was to call a service when the component is mounted. But notice that there is no dependencies array passed as the second parameter to useEffect. It means that the function will be called each time the component is rendered. Here we update a state when the request is completed, immediately triggering a new call.

What we should have done is to pass an empty array as the second parameter to ensure we call the function only once:

useEffect(() => {
// ...
}, [])
Result