Why is React UseEffect hook running on page reload

I have a UseEffect hook with a dependency array.

The issue is that the code inside runs every time I reload the page.

I have printed the values, so they should not be changing.

Here is the hook:

  useEffect(
    function () {
      console.log('This prints on page load every time');
      // Check if the user is upvoting
      if (didUserUpvote) {
        console.log('here');
        incrementUserUpvotes(answer.uidCreated);
        incrementAnswerUpvotes(answer.answerID);
        appendToArrInDoc('answers', answer.answerID, 'upvotedBy', user.uid);
        console.log('done');
      }
    },
    [didUserUpvote, answer.uidCreated, answer.answerID, user.uid]
  );

>Solution :

The useEffect is running every time you use reload a page because the variables are being initialized at the initial render, causing that useEffect to trigger.

Best way to fix this issue is to use a useRef Boolean (init at true). If it is true, set the useRef to false. If it is false, run the code you have in the useEffect.

Here’s how I would revise your code:


const init = useRef(true)
  useEffect(
    function () {
if(init.current){
init.current= false
}else{
      console.log('This prints on page load every time');
      // Check if the user is upvoting
      if (didUserUpvote) {
        console.log('here');
        incrementUserUpvotes(answer.uidCreated);
        incrementAnswerUpvotes(answer.answerID);
        appendToArrInDoc('answers', answer.answerID, 'upvotedBy', user.uid);
        console.log('done');
      }
}
    },
    [didUserUpvote, answer.uidCreated, answer.answerID, user.uid]
  );```

Leave a Reply