Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]
  );```
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading