J_dev
J_dev

Reputation: 65

I tried this code i already passed dependency in useEffect but the api call again and again after 3/4 second

Below code i try to make get response from api and put in Movie Component. but the problem is that api hit again and again i don't why this happened.here screen shot of api call


  const [loading, setloading] = useState(false);
  const [movielist, setmovielist] = useState([]);

  const [err, seterr] = useState("");

  const fetchMoviesHandler = useCallback(async () => {
    setloading(true);
    try {
      const reponse = await fetch("https://swapi.dev/api/films");
      if (reponse.status != 200) {
        seterr("something is wrong");
      }
      const data = await reponse.json();
      const result = data.results;
      setmovielist(result);
   
    } catch (errr) {
    
    }
  });

  useEffect(() => {
    fetchMoviesHandler();
  }, [fetchMoviesHandler]);

  return (
    <div>
      {movielist.map((movie) => {
        return <Movie key={movie.episode_id} title={movie.title} />;
      })}
    </div>
  );
};

Upvotes: 0

Views: 57

Answers (1)

David
David

Reputation: 218818

This is returning a new instance of the function on every render:

const fetchMoviesHandler = useCallback(async () => {
  // your function
});

Which will trigger the useEffect on every render, since this function is in its dependency array.

To tell useCallback to memoize the function and keep the same instance across multiple renders, it also needs a dependency array. For example:

const fetchMoviesHandler = useCallback(async () => {
  // your function
}, [setloading, setmovielist, seterr]);

Or, at the very least, an empty dependency array:

const fetchMoviesHandler = useCallback(async () => {
  // your function
}, []);

Which would essentially create one instance of the function and always use it for the life of the component.

Upvotes: 1

Related Questions