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

Viewed 80

I came across this error int he console. I had a look through the previous questions but they were not much help. Anyone know how I have caused this infinite loop?

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

import logo from './logo.svg';
import './App.css';
import Movie from './components/Movie'
import React, { useEffect, useState } from 'react';

  const FEATURED_API = "https://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&api_key=04c35731a5ee918f014970082a0088b1&page=1"
  const IMG_API = "https://image.tmdb.org/t/p/w1280"
  const SEARCH_API = "https://api.themoviedb.org/3/search/movie?&api_key=04c35731a5ee918f014970082a0088b1&query="


  function App() {
    const [movies, setMovies] = useState([]);

    useEffect(() => {
      fetch(FEATURED_API)
      .then((res) => res.json())
      .then((data) =>  {
        console.log(data)
        setMovies(data.results);
      });
    },[])
    setMovies(movies)
  

    return <div>{ movies.length > 0 && movies.map((movie) =>  <Movie/>)}</div>
    
}
export default App;

2 Answers

You can't set states outside functions or hooks in components.

Just remove the setMovies(movies) and it should work ;)

Keep in mind that the setMovies function queues a re-render that will take place as soon as the component has finished rendering. Given this behavior, if the setMovies function is placed outside of a function or a useEffect, it will get you stuck in a loop!

Related