title: componentDidUpdate() updating when state changes even if not in condition
body: <p>I have a unread property in my database that is used to calculate <code>unreadCount</code>. Now I am using Firebase and I have added a listener as to when the unread property changes in my <code>componentDidMount()</code>. Whenever the unread in firebase changes, it updates <code>props.user.unread</code> inside my <code>componentDidUpdate()</code>, which looks like -</p>
  <pre><code>componentDidUpdate(prevProps) {
      if(prevProps.user.unread !== this.props.user.unread ) {
          console.log(&quot;PREV PROPS&quot;,prevProps.user.unread)
          console.log(&quot;CURR PROPS&quot;,this.props.user.unread)
          this.setState({unreadCount:0})
          this.handleUnread(this.props.user.unread)
      }
  }
  </code></pre>
  <p>and <code>this.handleUnread</code> looks like-</p>
  <pre><code>handleUnread(obj) {
      for (var key in obj) {
          if (obj.hasOwnProperty(key)) {
              console.log(&quot;OBJ&quot;,obj[key])
              if(obj[key] &gt; 0) {
                  this.setState({unreadCount: this.state.unreadCount +1})
              }
          }
      }
  }
  </code></pre>
  <p>Here in <code>handleUnread(obj)</code>, I am updating <code>state.unreadCount</code> and this causes <code>componentDidUpdate(prevProps)</code> to run again even if my condition is not satisfied. my console logs look like <a href="https://i.stack.imgur.com/i7Nfl.png" rel="nofollow noreferrer">this</a>. Clearly <code>componentDidUpdate</code> is being called multiple times even if condition is not satisfied. My state changes every time <code>handleUnread()</code> is invoked and my question is does it invoke <code>handleUnread()</code> again in <code>componentDidUpdate</code>?</p>
  <p>If so why as if condition is not being satisfied. Also is there any other way to solve this problem instead of using <strong>state</strong> to measure <code>unreadCount</code>?</p>
  <h2>Update</h2>
  <p><code>handleUnread</code> is being called even with no state changes inside it and inside <code>componentDidUpdate</code>.</p>