You need to parse your news only when there is a change in new props. Add another useEffect with news as a dependency so it will be called when the news changes and then update your state there.

import React, {useEffect, useState} from 'react';
import Carousel from 'react-bootstrap/Carousel';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import {getNews} from "../../actions/news";
import Parser from 'rss-parser';

const NewsCarousel = ({getNews, news: {news, loading} }) => {

    const [getFeed, setFeed] = useState({
        feed: ''
    });

    useEffect(() => {
        const interval = setInterval(() => {
            getNews();
        }, 5000);
        return () => clearInterval(interval);
    }, [getNews]);

    useEffect(() => {
      const newsFeed = feed => setFeed({ ...getFeed, feed: feed });

      const parser = new Parser();
      parser.parseString(news, function(err, feed){
        if (!err) {
            newsFeed(feed);
        } else {
            console.log(err);
        }
      });
    }, [news]);

    return (
        <div className="dark-overlay">
        </div>
    );
};


NewsCarousel.propTypes = {
    getNews: PropTypes.func.isRequired,
    news: PropTypes.object.isRequired
};

const mapStateToProps = state => ({
    news: state.news
});

export default connect(mapStateToProps, {getNews}) (NewsCarousel);
Answer from Amit Chauhan on Stack Overflow
🌐
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

useState setting an infinite loop
Currently you set the onClick prop to the result of calling setOperation, so on each render it calls setOperation, which causes a rerender. Instead of passing in the result from calling setOperation, you want to pass in a function that calls setOperation More on reddit.com
🌐 r/reactjs
5
1
January 28, 2021
Infinite loop with useState + useRecoilState
a and b are two object states created by useState and useRecoilState respectively. Now follow code will cause a infinite loop. But if both a and b use useState or useRecoilState, or just remove one of them from dependence array, it will work correctly. More on github.com
🌐 github.com
1
March 10, 2023
reactjs - React useState Causing an infinite loop - Stack Overflow
1 Too many re-renders. React limits the number of renders to prevent an infinite loop. useState problem? More on stackoverflow.com
🌐 stackoverflow.com
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
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 › usestate setting an infinite loop
r/reactjs on Reddit: useState setting an infinite loop
January 28, 2021 -

Hello, I'm pretty new to React so I will try to explain my issue the best I can.

I have a component <Equation /> nested in <Picker />

I am trying to click a button inside of <Picker /> and have useState() update content inside of <Equation />.

I have a state set with const [operator, setOperator] = React.useState("+") inside of the Picker component that works fine , <Equation operation={operator} /> up until I add setOperator() to the onClick in the button.

<button className="Picker" onClick={(setText("Addition"), setOperator("+"))} >

Once I add this to the element I get this error

Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

Here is is a link to the Components https://gist.github.com/tbednarz/20f166f1ad8161d24b02ae30bded0cd2

🌐
Alex Sidorenko
alexsidorenko.com › blog › react-infinite-loop
3 ways to cause an infinite loop in React | Alex Sidorenko
July 5, 2021 - } function App() { const [count, setCount] = useState(0); setCount(1); // infinite loop · return ... } If you update the state directly inside your render method or the body of a functional component, it will cause an infinite loop.
🌐
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 - Eventually, this causes your application to crash · To solve this problem, we can make use of a useRefHook. This returns a mutable object which ensures that the reference does not change: const [count, setCount] = useState(0); //extract the ...
🌐
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 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; } }
Find elsewhere
🌐
GitHub
github.com › facebookexperimental › Recoil › issues › 2199
Infinite loop with useState + useRecoilState · Issue #2199 · facebookexperimental/Recoil
March 10, 2023 - a and b are two object states created by useState and useRecoilState respectively. Now follow code will cause a infinite loop. But if both a and b use useState or useRecoilState, or just remove one of them from dependence array, it will work correctly.
Author   Wxwind
🌐
Dmitri Pavlutin
dmitripavlutin.com › react-useeffect-infinite-loop
How to Solve the Infinite Loop of React.useEffect()
February 26, 2023 - The infinite loop is fixed with correct management of the useEffect(callback, dependencies) dependencies argument. Because you want count to increment when value changes, you can simply add value as a dependency of the side-effect: import { ...
🌐
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.
🌐
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 ...
🌐
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.
🌐
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

🌐
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.
🌐
GitHub
github.com › vercel › next.js › issues › 48822
useState Render Infinite Loop · Issue #48822 · vercel/next.js
April 25, 2023 - View how the component is re-rendered in an infinite loop. The useState hook update causes an infinite loop of refreshes when used in async client components.
Author   SamKomesarook
🌐
Reddit
reddit.com › r/reactjs › setstate hook causing infinite loop, not sure why!
r/reactjs on Reddit: setState hook causing infinite loop, not sure why!
September 15, 2019 -

This is the offending code:

const [users, setUsers] = useState([]);      

cognitoidentityserviceprovider.listUsers(params, (err, data) => {
if (err) {
  console.log(err);
} else {
  setUsers(data.Users);
  console.log(data);
}
  });

I really see no reason as to why this will send the code into an infinite loop but it does for some reason. I tried calling it within useEffect, but passing an empty array or [users] to it does nothing at all, and no array sends it into a loop again.

Is there something I'm just misunderstanding about Hooks here?

Top answer
1 of 5
6
So your function goes like this... call listUsers API. When that returns a none error value - set your state to data.Users. Your component re-renders... calls listUsers API. When that returns a none error value - set your state to data.Users. Your component re-renders... calls listUsers API. When that returns a none error value - set your state to data.Users. Your component re-renders... calls listUsers API. When that returns a none error value - set your state to data.Users. Your component re-renders... etc You probably need to just call listUsers API on initialisation. so useEffect that call with an array that contains [params] as the only value.
2 of 5
3
I suspect I know what is going on here, because I had an infinite loop happening inside my useEffect hook yesterday that I debugged. useEffect is definitely the correct thing to do here. The trick is that the return value from the function you pass in is significant -- it becomes the cleanup function. And if you are using a one-liner arrow function, the return value is the result of that single instruction. So my guess is that you did this: useEffect(() => listUsers(params, callback), [params]); which means that the api call, along with its callback, are called on each render. And whatever that function returns, (presumably is a function) gets called before each rerender! Change your code to be like this: useEffect(() => { listUsers(params, callback); }, [params]); Now the arrow function will not use its shorthand return syntax, meaning it will return nothing for the cleanup function which I'm guessing was triggering infinite setStates.
🌐
GitHub
github.com › facebook › react › issues › 24534
Bug: Creating a lazy component in a hook causes infinite loop · Issue #24534 · facebook/react
May 10, 2022 - React version: 18.1.0 to 18.2.0.next (latest available on code sandbox) Steps To Reproduce Have a component create a lazy component in a hook (useState/useMemo), Render the lazy component Infinite loop Link to code example: code sandbox ...
Published   May 10, 2022
🌐
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.
Top answer
1 of 1
1

If Value is calculated based on selected then this useEffect() is the issue:

useEffect(() => {
  setSelected([]);
}, [Value]);

As you said, it will cause an infinite loop as selected changes again and again, causing Value to change as well and the component keeps re-rendering.

Another place to look for error is in your <Select> component callbacks with onSelect and onDeselect. It is not a good idea to pass setSelected as parameter in most circumstances because useState hook has side effects. You don't provide the full code here, but I think it is likely that this also causes state change unstably in your component and causes the re-rendering.

Moreover, you have 2 useEffect() both have [selected] as dependency, so when selected changes it will cause duplicate rendering to the component as well. This is, however, not the cause to your primary issue.

Solution could be using only 1 useEffect() as follow:

Step 1. Regarding your <Select> component callback:

onSelect={handleSelect}
onDeselect={handleDeselect}

const handleSelect = (val) => {
  // think about removing setSelected
  onSelectValueMultiSelect(val, selected, setSelected, options);
  // move this here
  onChangeHandle(selected);
  // reset selected here if wanted
  setSelected([]);
}

const handleDeselect = (val) => {
  // think about removing setSelected
  onDeselectValueMultiSelect(val, selected, setSelected, options);
  // move this here
  onChangeHandle(selected);
  // reset selected here if wanted
  setSelected([]);
}

Step 2. Refactor your useEffect(), using only 1 instead of 3:

useEffect(() => {
  options.forEach(...);
  setChildrenOptions(children);
}, [selected]);

This is not the cleanest code, but this can be the right direction to solve your very particular issue without knowing much about the rest of the code.