title: React functional component state with external callback
body: <p>I have a functional React component that, among other things, sets up a Bluetooth connection and sets a <code>device</code> variable. It also sets up a callback listener for when Bluetooth responses come in. The listener needs to access <code>device</code>.</p>
  <pre class="lang-js prettyprint-override"><code>export default function App() {
    const [device, setDevice]... ?
    var deviceVar;
    
    const listener = (data) =&gt; {
      // needs device
      console.log(device, deviceVar);
      // 'device' is undefined but 'deviceVar' is correct
    }
  
    const scan = () =&gt; {
      setDevice(...);
      device = ...
      addListener(listener)
    }  
  }
  </code></pre>
  <p>Using <code>setState</code> is unreliable because the listener is triggered before (i.e.) <code>device</code> was updated.</p>
  <p>What is the correct way to handle this? Is there a more functional/hooks approach?</p>
  <p>Note that this question is NOT about using <code>useEffect</code> to provide my own callback on <code>device</code>. It is about an 'external' callback that I can't control the timing of.</p>