I'm struggling with the useEffect hook. I’m trying to fetch some data from an API and update the state, but I keep accidentally triggering infinite loops that crash my browser tab. I know it has something to do with the dependency array, but I'm confused about when to include objects or functions inside it. Any tips for a beginner?
3 answers
Infinite loops usually happen because you are updating a state inside useEffect that is also listed in the dependency array. When the state updates, the effect runs again, updates the state again, and so on. If you're fetching data, make sure your dependency array is empty [] if you only want it to run once on mount. If you must use objects or functions as dependencies, wrap them in useMemo or useCallback. This ensures the reference doesn't change on every render, which is a very common trap for developers new to the functional component paradigm.
Have you tried using a linter to catch these issues before you even hit the save button in your IDE?
Most of the time, you just need to ensure the dependency array is correctly populated. Leaving it empty is the most common fix for fetch calls.
Totally agree, Linda. Just remember that if your API call depends on a user ID, that ID must be in the array or the data won't update when the user changes!
James is right. The eslint-plugin-react-hooks is practically mandatory. It will highlight missing dependencies or tell you when a dependency will cause an unnecessary re-run. Also, if your state update depends on the previous state, always use the functional update pattern like setCount(prev => prev + 1). This allows you to remove the state variable from the dependency array entirely, which is the cleanest way to break the loop while keeping your logic intact.