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>  
}
🌐
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

Discussions

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
Bug: Infinite loop with useState and useEffect hooks
I am using default pattern for updating state if props changes. React version: 18.2.0 Steps To Reproduce Create component with useState and useEffect and some prop with array Update state value on ... More on github.com
🌐 github.com
9
January 26, 2024
Redux - how to stop infinite loop if you calling a redux action in useEffect?
Post here that useEffect you're having an issue with. More on reddit.com
🌐 r/reactjs
11
1
December 23, 2020
setState causing an infinite loop and I'm not sure why

Add a list of dependencies (which may be empty) to useEffect. As it stands, your useEffect is called on every render so you end up with something like

render → useEffect → generateRandomPotentialPartner → setState → render → useEffect → generateRandomPotentialPartner → setState → render

etc

More on reddit.com
🌐 r/reactjs
4
2
September 14, 2019
People also ask

How can I prevent an infinite loop in useEffect?
Use a proper dependency array, memoize functions and objects with useCallback or useMemo, and avoid unnecessary state updates within the effect.
🌐
dhiwise.com
dhiwise.com › blog › design-converter › preventing-react-useeffect-infinite-loop-simple-fixes
React UseEffect Infinite Loop: Common Causes and Solutions
Why is the dependency array important in useEffect?
The dependency array tells React when to run the effect, ensuring it runs only when necessary and preventing continuous re-renders.
🌐
dhiwise.com
dhiwise.com › blog › design-converter › preventing-react-useeffect-infinite-loop-simple-fixes
React UseEffect Infinite Loop: Common Causes and Solutions
What role does memoization play in preventing infinite loops?
Memoization stabilizes function and object references between renders, so they don't trigger useEffect unnecessarily.
🌐
dhiwise.com
dhiwise.com › blog › design-converter › preventing-react-useeffect-infinite-loop-simple-fixes
React UseEffect Infinite Loop: Common Causes and Solutions
🌐
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 › 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.
🌐
Perficient Blogs
blogs.perficient.com › 2024 › 12 › 16 › avoiding infinite loops when utilizing useeffect() in reactjs
Avoiding Infinite Loops When Utilizing useEffect() in ReactJS / Blogs / Perficient
December 16, 2024 - When no dependencies are specified, the effect runs after each render, resulting into infinite loop of updates, especially when state modifications are involved. ... When the component first renders, the useEffect runs.
🌐
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... and as soon as you enter the special word 'secret' the secrets counter increments. No infinite loop is created. That's a win! useEffect(callback, deps) is the hook that executes callback (the side-effect) after ...
Find elsewhere
🌐
Max Rozen
maxrozen.com › learn-useeffect-dependency-array-react-hooks
Preventing infinite re-renders when using useEffect and useState - Max Rozen
Changing state will always cause a re-render. By default, useEffect always runs after render has run.
🌐
Plain English
plainenglish.io › blog › 5-useeffect-infinite-loop-patterns-2dc9d45a253f
5 useEffect Infinite Loop Patterns
July 23, 2021 - The shallow comparison for the function will always give false. To fix this issue, we need to use another infinity stone called useCallback. useCallback return a memoized version of callback, which only change when the dependencies change.
🌐
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 - So, similar to using useEffect, we can use an empty dependency array to ensure the function isn't being re-created between renders. This prevents the effect from running in an infinite loop when a function is used as a dependency.
🌐
DhiWise
dhiwise.com › blog › design-converter › preventing-react-useeffect-infinite-loop-simple-fixes
React UseEffect Infinite Loop: Common Causes and Solutions
March 20, 2025 - React continuously recreates reference ... Dependency Array: If the second argument (dependency array) is omitted or incorrectly defined, useEffect will run on every render, causing an infinite loop....
🌐
Medium
medium.com › @andrewmyint › infinite-loop-inside-useeffect-react-hooks-6748de62871
How to Fix the Infinite Loop Inside “useEffect” (React Hooks)
June 4, 2023 - How to Fix the Infinite Loop Inside “useEffect” (React Hooks) If you start using React-Hooks, your component might need a life cycle method at some point. And that is when you start using …
🌐
DEV Community
dev.to › arikaturika › the-traps-of-useeffect-infinite-loops-836
The traps of useEffect() - infinite loops - DEV Community
January 14, 2021 - 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 ...
🌐
CodingDeft
codingdeft.com › posts › react-useeffect-infinite-loop
How to solve Infinity loop in React's useEffect | CodingDeft.com
The useEffect hook checks if the 2 objects are equal. As 2 objects are not equal in JavaScript, even though they contain the same properties and values, the useEffect runs again causing infinite loop.
🌐
Medium
medium.com › @conboys111 › how-to-prevent-infinite-loops-in-reacts-useeffect-hook-a-beginner-s-guide-b78652caf66a
How to Prevent Infinite Loops in React’s useEffect Hook: A Beginner’s Guide | by myHotTake | Medium
December 5, 2024 - But here’s the trick: if I accidentally put something in the dependency array that changes every time the sensor sends a signal — like the status of the light itself — I’ve created a feedback loop. The lighthouse light turns on, the sensor detects that change, sends another signal, and I’m stuck in a storm of infinite signals. So, to keep things calm and functional, I double-check the dependencies I give to my sensor. I make sure I’m only reacting to meaningful weather changes — like real storms — and not my own actions. This keeps the lighthouse running smoothly, just like my useEffect stays free of infinite loops.
🌐
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.
Author   eashish93
🌐
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
🌐
YouTube
youtube.com › watch
Why useEffect causes infinite loops - fix it with useCallback - YouTube
Just a little example of how to fix an infinite useEffect loop caused by fixing a eslint exhaustive-deps warning------------🔔 Newsletter http://eepurl.com/...
Published   May 18, 2022
🌐
Sean C Davis
seancdavis.com › posts › avoiding-an-infinite-loop-in-the-useeffect-hook
Avoiding an Infinite Loop in the useEffect Hook | Sean C Davis
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>; };
🌐
JavaScript in Plain English
javascript.plainenglish.io › 5-useeffect-infinite-loop-patterns-2dc9d45a253f
5 useEffect Infinite Loop Patterns | by Naveen DA | JavaScript in Plain English
July 23, 2021 - The shallow comparison for the function will always give false. To fix this issue, we need to use another infinity stone called useCallback. ... As you might know, the shallow comparison for two is always false, so passing dependencies as an array will also lead to 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 update the state directly inside your render method or the body of a functional component, it will cause an infinite loop. State updates → triggers re-render → state updates → triggers re-render → and so on...