Passing an empty array as the second argument to useEffect makes it only run on mount and unmount, thus stopping any infinite loops.

useEffect(() => {
  setIngredients({});
}, []);

This was clarified to me in the blog post on React hooks at https://www.robinwieruch.de/react-hooks/

Answer from WhiteFluffy on Stack Overflow
Top answer
1 of 16
231

Passing an empty array as the second argument to useEffect makes it only run on mount and unmount, thus stopping any infinite loops.

useEffect(() => {
  setIngredients({});
}, []);

This was clarified to me in the blog post on React hooks at https://www.robinwieruch.de/react-hooks/

2 of 16
135

Had the same problem. I don't know why they not mention this in docs. Just want to add a little to Tobias Haugen answer.

To run in every component/parent rerender you need to use:

  useEffect(() => {

    // don't know where it can be used :/
  })

To run anything only one time after component mount(will be rendered once) you need to use:

  useEffect(() => {

    // do anything only one time if you pass empty array []
    // keep in mind, that component will be rendered one time (with default values) before we get here
  }, [] )

To run anything one time on component mount and on data/data2 change:

  const [data, setData] = useState(false)
  const [data2, setData2] = useState('default value for first render')
  useEffect(() => {

// if you pass some variable, than component will rerender after component mount one time and second time if this(in my case data or data2) is changed
// if your data is object and you want to trigger this when property of object changed, clone object like this let clone = JSON.parse(JSON.stringify(data)), change it clone.prop = 2 and setData(clone).
// if you do like this 'data.prop=2' without cloning useEffect will not be triggered, because link to data object in momory doesn't changed, even if object changed (as i understand this)
  }, [data, data2] )

How i use it most of the time:

export default function Book({id}) { 
  const [book, bookSet] = useState(false) 

  const loadBookFromServer = useCallback(async () => {
    let response = await fetch('api/book/' + id)
    response  = await response.json() 
    bookSet(response)
  }, [id]) // every time id changed, new book will be loaded

  useEffect(() => {
    loadBookFromServer()
  }, [loadBookFromServer]) // useEffect will run once and when id changes


  if (!book) return false //first render, when useEffect did't triggered yet we will return false

  return <div>{JSON.stringify(book)}</div>  
}
🌐
GitHub
github.com › facebook › react › issues › 28109
Bug: Infinite loop with useState and useEffect hooks · Issue #28109 · facebook/react
January 26, 2024 - export function List({ items = [] }) { const [itemsState, setItemState] = useState([]); useEffect(() => { setItemState(items); // this line starts infinite loop }, [items]); return <div>Length: {itemsState.length}</div>; } infinite loop · set value to state if prop items changes ·
Author   mkozachok
Discussions

useEffect causes an infinite loop?
TL;DR) Add [] as a second argument to useEffect useEffect() with no second argument will run every render. This means every time the request completes and you force a rerender by calling setItems, you will issue another request. The solution to this is the use the optional second argument to useEffect known as the dependency list. This will make it only trigger when that deps list changes. You can use an empty argument if your fetch is based on nothing []. If it changes then you can add any immutable types to that list. useEffect(() => { sanityClient .fetch( `*[_type == "issue"] | order(publishedAt desc) { title, slug, description, frontCover{ asset->{ _id, url } } }` ) .then((data) => { setItems(data); }) .catch(console.error); }, []); See the very last line that I changed above ^ See more on the official docs for useEffect https://beta.reactjs.org/reference/react/useEffect A side note, you may want to hoist your fetch method up to make it easier to read your code like so: const fetchSanity = () => sanityClient .fetch( `*[_type == "issue"] | order(publishedAt desc) { title, slug, description, frontCover{ asset->{ _id, url } } }` ) More on reddit.com
🌐 r/reactjs
16
0
January 21, 2023
reactjs - React UseState hook causing infinite loop - Stack Overflow
I am using ReactJs to grab an RSS ... it on the webpage. I am using both useEffect and useState hook for this purpose as I am passing the JSON string in the useState hook variable, however. It kind of works but it produces an infinite loop.... More on stackoverflow.com
🌐 stackoverflow.com
Infinite loop in useEffect using blank object or array
Using React Version: 16.8.4 When using blank object or array as a setter for function inside useEffect does cause infinite loop. However using string or number does not trigger this. Here's the min... More on github.com
🌐 github.com
8
March 13, 2019
reactjs - Setting state inside useEffect triggers infinite loop - Stack Overflow
Im creating a custom autosave hook for my project that uses react-hook-form. Inside this custom hook I want to add two pieces of state, isSaving and saveMessage The custom hook works fine until I c... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Max Rozen
maxrozen.com › learn-useeffect-dependency-array-react-hooks
Preventing infinite re-renders when using useEffect and useState - Max Rozen
You'd cause an infinite loop. import React, { useEffect, useState } from 'react'; export default function DataDisplayer(props) { const [data, setData] = useState(''); useEffect(() => { const getData = async () => { const response = await ...
🌐
GitHub
github.com › facebook › react › issues › 17688
useEffect and useState infinite loop inconsistencies · Issue #17688 · facebook/react
December 22, 2019 - What is the current behavior? When objects are used as dependency for useEffect, they are ignored and cause automatic rerendering. This is problematic when there is useState inside the useEffect, as it creates an infinite loop.
🌐
Indersingh
indersingh.com › node › 584
useEffect is Executed in an endless loop react function component | Inder Singh - Drupal Frontend Developer | India
The infinite loop is fixed by using dependency argument correctly while calling useEffect(callback, dependencies). In following example, adding [value] parameter as a dependency of useEffect(..., [value]) call, the "login" state variable is updated only when [value] is changed.
🌐
Medium
medium.com › @andrewmyint › infinite-loop-inside-useeffect-react-hooks-6748de62871
How to Fix the Infinite Loop Inside “useEffect” (React Hooks)
June 4, 2023 - The code snippet below is an example of using Effect Hook, but it has an infinite loop behavior. ... In a nutshell, the component “DisplayName” has two states, which are “name” and “userId”. And it has a function called “fetchUser()” which handles fetching data from the API and setting the “name”. Then, there is "useEffect(),” which will call “fetchUser()” after rendering a DOM element. The “useEffect()”, will run after the initial render, then invoke the “fetchUser()”. Inside “fetchUser”, it will update the state “name” on line 9.
🌐
Reddit
reddit.com › r/reactjs › useeffect causes an infinite loop?
r/reactjs on Reddit: useEffect causes an infinite loop?
January 21, 2023 -

Hey!! First time building a website and have ran into this issue when trying to fetch content from Sanity Studio.

Here's the link: https://pastebin.com/3iL0gpBt

Copying what I think is the relevant part of the code

export default function IssuesList() {
  const [items, setItems] = useState([]);

  useEffect(() => {
    sanityClient
      .fetch(
        `*[_type == "issue"] | order(publishedAt desc) {
      title,
      slug,
      description,
      frontCover{
        asset->{
          _id,
          url
        }
      }
    }`
      )
      .then((data) => {
        setItems(data);
      })
      .catch(console.error);
  });

  return (
    <div css={issuesListSx}>
      <Frame path={[{ name: "Issues", slug: "/issues" }]}>
        <Grid gap={2} columns={[1, null, 2]} className="issuesGrid">
          {items.map((issue) => {
            return (
              <div className="issueItem" key={issue.title}>
                <Link to={"/issues/" + issue.slug.current}>
                  <div>{issue.title}</div>
                  {issue.frontCover && "asset" in issue.frontCover && (
                    <img src={issue.frontCover.asset.url} alt="" />
                  )}
                </Link>
              </div>
            );
          })}
        </Grid>
      </Frame>
    </div>
  );
}

E: Fixed!! Had to add an empty array as a second parameter to useEffect

Find elsewhere
🌐
LogRocket
blog.logrocket.com › home › how to solve the react useeffect hook’s infinite loop patterns
How to solve the React useEffect Hook's infinite loop patterns - LogRocket Blog
June 4, 2024 - If your useEffect function does not contain any dependencies, an infinite loop will occur. ... function App() { const [count, setCount] = useState(0); //initial value of this useEffect(() => { setCount((count) => count + 1); //increment this ...
🌐
Dmitri Pavlutin
dmitripavlutin.com › react-useeffect-infinite-loop
How to Solve the Infinite Loop of React.useEffect()
February 26, 2023 - In this post, I'll describe the common scenarios that generate infinite loops and how to avoid them. Let's say you want to create a component having an input field, and also display how many times the user changed that input. Here's a possible implementation of <CountInputChanges> component: ... value state variable holds the input value, and the onChange event handler updates the value state when the user types into the input. I decided to update the count variable using useEffect() hook.
🌐
CodingDeft
codingdeft.com › posts › react-useeffect-infinite-loop
How to solve Infinity loop in React's useEffect | CodingDeft.com
In the above code, we are calling setCounter inside the useEffect hook and the counter increments. As the state changes, the component gets re-rendered and useEffect runs again and the loop continues. The useEffect hook runs again as we did not pass any dependency array to it and causes an infinite loop.
🌐
Alex Sidorenko
alexsidorenko.com › blog › react-infinite-loop
3 ways to cause an infinite loop in React | Alex Sidorenko
July 5, 2021 - If you keep updating a state inside useEffect with a property you update set as a dependency, it will cause an infinite loop.
🌐
DEV Community
dev.to › oyedeletemitope › three-ways-to-cause-infinite-loops-when-using-useeffect-in-react-and-how-to-prevent-them-3ip3
Three Ways to Cause Infinite Loops When Using UseEffect in React and How to Prevent Them - DEV Community
November 17, 2024 - Since objects in JavaScript are reference types, the useEffect hook will run on every render because the reference to the object changes on every render, even if the content of the object remains the same.
🌐
DhiWise
dhiwise.com › blog › design-converter › preventing-react-useeffect-infinite-loop-simple-fixes
React UseEffect Infinite Loop: Common Causes and Solutions
March 20, 2025 - A correct dependency array ensures ... Inside the Effect: Using setState within the effect causes a re-render, which triggers the effect again, leading to an infinite loop if not controlled properly....
🌐
freeCodeCamp
freecodecamp.org › news › prevent-infinite-loops-when-using-useeffect-in-reactjs
How to Prevent Infinite Loops When Using useEffect() in ReactJS
April 26, 2023 - One common mistake that can cause infinite loops is not specifying a dependency array. useEffect checks if the dependencies have changed after every render of the component. So, when no dependencies are provided, the effect will run after every ...
🌐
GitHub
github.com › facebook › react › issues › 15096
Infinite loop in useEffect using blank object or array · Issue #15096 · facebook/react
March 13, 2019 - Using React Version: 16.8.4 When using blank object or array as a setter for function inside useEffect does cause infinite loop. However using string or number does not trigger this.
Author   eashish93
🌐
IQCode
iqcode.com › code › javascript › infinite-loop-in-useeffect
Infinite loop in useEffect Code Example
September 13, 2021 - setstate in useeffect hook infinite ... react stop infinite useeffect loop infinite loop in react useEfect fir loop inside useEffect if state is updated in useeffect hook infinite loop useState inside useeffect infinite loop useeffect is going in infinite loop is useEffect supposed ...
🌐
Medium
medium.com › @kunaltandon.kt › useeffect-setstate-the-infinite-loop-4fa0b6dba637
useEffect & setState — The infinite loop! | by Kunal Tandon | Medium
September 6, 2023 - Ensuring proper state management and dependency handling is the key to a smooth React application. ... Here’s what happens: changing the state triggers useEffect, which then triggers setState. And guess what?
🌐
Stack Overflow
stackoverflow.com › questions › 77887756 › setting-state-inside-useeffect-triggers-infinite-loop
reactjs - Setting state inside useEffect triggers infinite loop - Stack Overflow
By removing the setIsSaving and the setSaveMessage the hook works as intended. I read multiple posts about this issue of state inside useEffect triggering infinite loop but in those cases the changed state was a part of the dependencies of useEffect, which is not in this case.