Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function component keeps rerendering over and over

My react function component keeps re-rendering itself over and over until the browser crashes.

The only solution i could find was entering [] with my constant at the end of useEffect().

function getNestedObject(nestedObj, pathArr) {
  return pathArr.reduce(
    (obj, key) => (obj && obj[key] !== "undefined" ? obj[key] : undefined),
    nestedObj
  );
}

function Genres() {
  const [genreList, setgenreList] = useState(0);

  useEffect(() => {
    let results = "";
    axios({
      url: "https://api.themoviedb.org/3/genre/movie/list?",
      method: "GET",
      responseType: "json",
      params: {
        api_key: "00000000000",
        language: "en-US"
      }
    }).then(result => (results = result.data.genres));

    let a = [];
    for (let i = 0; i < 10; i++) {
      let name = getNestedObject(results, [i, "name"]);
      a.push(name);
    }
    setgenreList(a);
    console.log(genreList);
  }, [genreList]);
  return <div>test</div>;
}

I have also tried it without the useEffect which gives the same looping result.

I have <Genres /> down in the render.

like image 339
iLoveSpicyNoodles Avatar asked Apr 26 '26 02:04

iLoveSpicyNoodles


2 Answers

Its happening because of you are calling

    setgenreList(a);

at useffect , genreList change its state, UseEffect run again

when you are writing

  useEffect(() => {}, [genreList])

then it will be called everytime when you call its setter setgenreList

you may write

useEffect(() => {
    //code here
    }, [])
like image 70
Rahul Avatar answered Apr 28 '26 15:04

Rahul


Actually, you are generating an empty array every time and updating the state with a newly generated array every time, hence useEffect loops infinitely (check [] === []). Also you have an obvious error in the code: the state update doesn't depend on axios result at all, since you don't wait for response results ("then" block is executed after setgenreList(a)). Use state update inside "then" function.

like image 20
Sim Dim Avatar answered Apr 28 '26 16:04

Sim Dim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!