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>  
}
🌐
Dmitri Pavlutin
dmitripavlutin.com › react-useeffect-infinite-loop
How to Solve the Infinite Loop of React.useEffect()
February 26, 2023 - Type some words into the input... ... No infinite loop is created. That's a win! useEffect(callback, deps) is the hook that executes callback (the side-effect) after deps changes....
Discussions

For loop inside useEffect (unobvious behaviour)
Here is my code: https://codesandbox.io/s/useeffect-3zkw27 ... You can see that rendered value changes much faster when the loop is inside if condition. Any ideas why? UPDATE. Ok, I have decided to change my code a bit in order to run for loop only once. Let's say I have for loop either inside ... More on stackoverflow.com
🌐 stackoverflow.com
How to use useEffect and for loop to generate multiple JSX elements
I want to use useEffect and for-loop to generate multiple JSX elements but nothing is rendered in this case. warning code: “React Hook useEffect has a missing dependency: ‘renderInfoCard’. Either include it or remove the dependency array react-hooks/exhaustive-deps” Answer I wouldnR… More on javascript.tutorialink.com
🌐 javascript.tutorialink.com
1
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. More on github.com
🌐 github.com
8
March 13, 2019
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
🌐
Medium
medium.com › @andrewmyint › infinite-loop-inside-useeffect-react-hooks-6748de62871
How to Fix the Infinite Loop Inside “useEffect” (React Hooks)
June 4, 2023 - As a result, “useEffect()” will run again and update the state. Next, the whole process repeats again, and you're trapped inside an infinite loop.
🌐
Stack Overflow
stackoverflow.com › questions › 76966026 › for-loop-inside-useeffect-unobvious-behaviour
For loop inside useEffect (unobvious behaviour)
But I thought that the second loop shouldn't have that much of an impact since useEffect is asynchronous and there is no rerender after the second loop (if for loop is outside) I mean that the whole chain: click button -> setState(0) -> browser paints new value -> UseEffect (for loop, setState(random)) -> browser paints new value -> UseEffect (w for loop) or UseEffect (w/o for loop). I would expect that only the first loop matters in the ideal world.
🌐
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 - Since the reference value of the person object changes on every render, React re-runs useEffect · As a result, this invokes setCount on every update cycle. This means that we now have an infinite loop
🌐
DEV Community
dev.to › manojms › how-to-fix-useeffect-hook-executing-in-an-endless-loop-1oga
How to Fix useEffect Hook executing in an endless loop? - DEV Community
October 16, 2021 - useEffect(() => { Document.title = `You clicked ${count} times`; },[count]); // Only re-run the effect if count changes · But what if we only want the hook to execute when the component is mounted and rendered the first time? We already know, if we don’t pass an array of dependencies, the Hook will be executed in a loop.
Find elsewhere
🌐
Plain English
plainenglish.io › blog › 5-useeffect-infinite-loop-patterns-2dc9d45a253f
5 useEffect Infinite Loop Patterns
July 23, 2021 - When you run this code, it will throw Maximum update depth exceeded which means the code having an infinite loop. Since useEffect uses the shallow comparison for the compare the values.
🌐
IQCode
iqcode.com › code › javascript › infinite-loop-in-useeffect
Infinite loop in useEffect Code Example
September 13, 2021 - setstate in useeffect hook infinite ... with useEffect loop with useEffect react hooks setstate in useeffect infinite loop react usestate in useeffect infinite loop for loop in react js useeffect react native useeffect infinite loop how to make useeffect infinite but not loop ...
🌐
DEV Community
dev.to › collegewap › how-to-solve-infinity-loop-in-reacts-useeffect-5d6e
How to solve Infinity loop in React's useEffect? - DEV Community
March 28, 2023 - 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.
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-avoid-infinite-loops-when-using-useeffect-in-reactjs
How To Avoid Infinite Loops When Using useEffect() in ReactJS? | GeeksforGeeks
October 14, 2024 - Avoid infinite loops in useEffect() by providing appropriate dependencies in the dependency array. Use an empty array for one-time execution, a specific state value for triggering effect, or multiple state values with conditions for selective ...
🌐
Andreas Reiterer
andreasreiterer.at › home › why is my useeffect hook executed in an endless loop?
Why is my useEffect Hook executed in an endless loop? » Andreas Reiterer
February 12, 2019 - Learn how your component using the useEffect Hook can end up re-rendering itself in a loop and how the power of dependencies can stop it.
🌐
GitHub
github.com › facebook › react › issues › 15096
Infinite loop in useEffect using blank object or array · Issue #15096 · facebook/react
March 13, 2019 - function Example() { const [count, setCount] = useState(0); const [foo, setFoo] = useState({}); useEffect(() => { console.log("Infinite Loop"); setCount(100); // doesn't cause infinite loop. // but this does // setFoo({}); // or setFoo([]); }); return <div />; } I don't know if it's a bug or default behaviour because in earlier version of react (in v16.7.0-alpha.0), both string and number also causing infinite loop which seems to be fixed in latest one. ... No fields configured for issues without a type.
Author   eashish93
🌐
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

🌐
DEV Community
dev.to › arikaturika › the-traps-of-useeffect-infinite-loops-836
The traps of useEffect() - infinite loops - DEV Community
January 14, 2021 - While doing data fetching, it happened that I forgot to provide the second argument to the hook (the dependency array). If we don't specify the dependency array, the effect will run after every render (if we set a state inside the hook, this will cause the component to re-render and the code inside the hook will run again; the state will get updated, a re-render happens, the effect will run again and so on, we got ourselves an infinite loop). Remove the [] argument inside the useEffect() and see what happens in the console.
🌐
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 - This ensures the effect doesn't run in an infinite loop since the dependency in the useEffect hook will no longer change with each render of the component. Note that you can also change the value of the data.current property. For example:
🌐
SegmentFault
segmentfault.com › a › 1190000040330842 › en
How to solve the infinite loop of React.useEffect()
July 12, 2021 - It generates an infinite loop of component re-rendering. After the initial rendering, useEffect() executes the side effect callback function of the updated state. Status update triggers re-rendering.
🌐
Max Rozen
maxrozen.com › learn-useeffect-dependency-array-react-hooks
Preventing infinite re-renders when using useEffect and useState - Max Rozen
What if you wanted to let users decide which id they wanted to query, and forgot to add the dependency array? 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 fetch(`https://swapi.dev/api/people/${props.id}/`); const newData = await response.json(); setData(newData); }; getData(); // highlight-next-line }); //<-- Notice the missing dependency array if (data) { return <div>{data.name}</div>; } else { return null; } }
🌐
Stack Overflow
stackoverflow.com › questions › 71764707 › how-to-stop-the-for-loop-inside-useeffect-in-react-js
reactjs - How to stop the for loop inside useEffect in react js? - Stack Overflow
April 6, 2022 - const getData = async () => { const balance = await contract.methods.balanceOf(accountId).call(); setBalance(balance); let storeList = []; for (let i = 0; i<balance; i++) { try { const token = await contract.methods.tokenOfOwnerByIndex(accountId , i).call(); let data = await contract.methods.tokenURI(token).call(); const receivedData = await fetch(data); let jsonData = await receivedData.json(); storeList.push(jsonData); storeList.sort((a, b) => a.tokenId-b.tokenId); setList([...storeList]); } catch(error) { cogoToast.error(`Error caused in fetching data of ${i} number token`); } } setList(sto
🌐
Medium
medium.com › @kunaltandon.kt › useeffect-setstate-the-infinite-loop-4fa0b6dba637
useEffect & setState — The infinite loop! | by Kunal Tandon | Medium
September 6, 2023 - Here’s what happens: changing the state triggers useEffect, which then triggers setState. And guess what? This merry-go-round keeps going, causing an infinite loop of updates.