Home

Avoiding an Infinite Loop in the useEffect Hook

It’s surprisingly easy to create infinite loops in React.

If you’ve encountered an infinite loop in React, it’s almost certain that you’ve added code inside an effect hook without specifying a dependency. Unfortunately, React doesn’t tell you that you’re doing anything wrong.

Here’s a simple example in which you update and render a counter.

import { useEffect, useState } from "react";

export const MyInfiniteLoop = () => {
const [count, setCount] = useState(0);

useEffect(() => setCount(count + 1));

return <div>Count: {count}</div>;
};

In this case, here’s what happens:

  1. Component renders.
  2. useEffect() runs.
  3. count is incremented by 1. This triggers a re-render. (Go to #1.)

Avoiding the Hook

The way to get around this is to specify an array of dependencies to the effect hook. By default, there are no dependencies, which means it will run every time the component renders.

You can instead tell the hook that it has no dependencies, and so it will only render a single time.

import { useEffect, useState } from "react";

export const MyInfiniteLoop = () => {
const [count, setCount] = useState(0);
// Use an empty array as the second arg to specify no dependencies
useEffect(() => setCount(count + 1), []);
return <div>Count: {count}</div>;
};

Catching Infinite Loops Earlier

If you’re using eslint, as is a common practice in modern JavaScript projects, then you can make use of the eslint-plugin-react-hooks plugin, which will throw warnings when there is a risk for more renders than intended.

Let's Connect

Keep Reading

How to Add SVG Icons to a React Project

Vector icons have become an essential part of nearly every web project. Stay consistent and organized when adding icons to a React project.

Oct 06, 2022

React May Not Be the Best Tool for Your Project

React is a great tool with a massive developer community. It comes with its own benefits and challenges. And yet, there may be tooling that is more suitable to your project.

Apr 19, 2023

Pick the React framework that best serves your project

When you’ve decided to use React, take a moment to consider the site framework (for building, routing, and other dev APIs) that best suits your project.

Apr 03, 2025