I don't know why I'm getting a useEffect infinite loop

Viewed 64
 const handleLike = async () => {
    await likeTweet(tweet._id, user._id);
  };

  useEffect(() => {
    const fetch = async () => {
      const response = await fetchLikes(tweet._id);
      setTweetLikes(response.data);
      console.log("useEffect");
    };
    fetch();
  }, [handleLike]);

I'm just declaring the dependencies function, not excecuting it. I don't know why it's remounting the component

1 Answers

You should remove handleLike from the dependency list. This is because, since you're setting the state inside the effect, the component will re-render. And this will run the function body again, which means that the handleLike function is defined again. And so the useEffect runs again.

Also, it seems like handleLike shouldn't be a dependency anyway, since you're not using it inside the effect.

If you must have it as a dependency, use the useCallback hook to prevent it from being redefined on every render.

Related