title: useCallback with state dependency causes infinite loop
body: <p>I’ve got a <code>useCallback</code> that updates state, but because it requires that state as a dependency, it creates an infinite loop when it updates the state. I’m using <a href="https://github.com/immerjs/use-immer" rel="nofollow noreferrer"><code>useImmer</code></a> here, but it happens when using plain <code>useState</code>, too.</p>
  <pre class="lang-js prettyprint-override"><code>const [panels, updatePanels] = useImmer({
      activePanel: 0,
      validPanels: [],
  });
  const onValidatePanel = useCallback(isValid =&gt; {
      const panelIndex = panels.validPanels.indexOf(panels.activePanel);
  
      // Add
      if (panelIndex === -1 &amp;&amp; isValid) {
          updatePanels(draft =&gt; {
              draft.validPanels.push(draft.activePanel);
          });
      // Remove
      } else if (panelIndex &gt; -1 &amp;&amp; !isValid) {
          updatePanels(draft =&gt; {
              draft.validPanels.splice(panelIndex, 1);
          });
      }
  }, [panels]);
  </code></pre>
  <p>Basically when an index is added or removed, <code>panels</code> changes, triggers <code>onValidatePanel</code> again, and re-adds the index, and on and on…</p>
  <p>How might I work around this?</p>