title: Nextjs Listener with callback executes itself
body: <p>I have been working on a real-time notification system for my nextjs app. It is working great, and I call it like this in each page:</p>
  <pre class="lang-js prettyprint-override"><code>
  export default function Bot({user}) {
  
      startNotifications(user)
  }
  
  </code></pre>
  <p>The function itself looks like this</p>
  <pre><code>    const userID = getUserID(user)
      const pubnub = new PubNub({
          subscribeKey: subKey,
          uuid: userID
      });
  
      const { asPath } = useRouter()
      pubnub.unsubscribeAll();
      pubnub.addListener({
          signal: function(signal) {
              const message = signal.message
              if (message[0] == &quot;bot&quot;) {
                  Notiflix.Notify.Info(notificationMessage);
  
                  if (check if url is correct here) {
                      callback()
                      return
                  }
  
              }
  
          }
      })
  
      pubnub.subscribe({
          channels: [&quot;announcements&quot;, userID.toString()],
      });
  </code></pre>
  <p>But when i try to add a callback funtion to change the state, depending on notification like this:</p>
  <pre><code>export default function Bot({user}) {
  
      startNotifications(user, changeState)
  
  
      const [value, setValue] = useState(true)
  
      function changeState(){
        console.log(&quot;changing state&quot;)
    
        setValue(false)
      }
  }
  </code></pre>
  <p>The code works fine, and the state is getting changed, but for some reason the code loops over itself and doubles the number of listeners each notification. In the startNotifications function I even tried to unsubscribe and resubscribe, but that doesn't work either. It looks like this
  (First notification)</p>
  <p><a href="https://i.stack.imgur.com/rTxGH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rTxGH.png" alt="1. Image" /></a></p>
  <p>And then if I do it a couple more times the 4. Notification looks like this:</p>
  <p><a href="https://i.stack.imgur.com/71c3V.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/71c3V.png" alt="2. Image" /></a></p>
  <p>I am pretty much at the end of trying. I have tried to implement the startNotifications in the same file, but that does the same thing.</p>
  <p>If anyone has a solution to this (its probably something very obvious that I don't know) please let me know. Have a great day.</p>