title: Using setTimeout to avoid re-renders in React
body: <p>There is a pattern that I use often that I feel must be an anti-pattern but I don't know a better alternative.</p>
  
  <p>Occasionally my components may receive one or more events that mean that a re-render is necessary.  Sometimes it is the case that I do not know how many times the event handlers will be called.  To prevent multiple re-renders as a result of many calls to the handlers I do something like this:</p>
  
  <pre><code> _myEventHandler() { // may be called multiple times between renders
     if (!this._updateQueued) {
       this._updateQueued = true;
       this._updateTimer = setTimeout(() =&gt; {
         this._updateQueued = false;
         this.forceUpdate();
       }, 0);
     }
   }
  </code></pre>
  
  <p>The problem here is I feel it can't be performant due to the latency between code stopping and the event loop starting.  </p>
  
  <p>A real world example of this is when I am using react-visibility-sensor and I have multiple elements change their visibility at once, I don't want to re-render for each element, instead I want just one re-render once all the updates have been received.</p>
  
  <p>Is there another better way to deal with multiple calls?</p>
  
  <p>BTW: if you are going to use the above hack don't forget to call <code>clearTimout(this._updateQueued)</code> in your <code>componentWillUnmount</code></p>