How do I window removeEventListener using React useEffect : <p>In React Hooks documents it is shown how to removeEventListener during the component's cleanup phase. <a href="https://reactjs.org/docs/hooks-reference.html#conditionally-firing-an-effect" rel="noreferrer">https://reactjs.org/docs/hooks-reference.html#conditionally-firing-an-effect</a></p>

<p>In my use case, I am trying to removeEventListener conditional to a state property of the functional component.</p>

<p>Here's an example where the component is never unmounted but the event listener should be removed:</p>

<pre><code>function App () {
  const [collapsed, setCollapsed] = React.useState(true);
  React.useEffect(
    () =&gt; {
      if (collapsed) {
        window.removeEventListener('keyup', handleKeyUp); // Not the same "handleKeyUp" :(
      } else {
        window.addEventListener('keyup', handleKeyUp);
      }
    },
    [collapsed]
  );
  function handleKeyUp(event) {
    console.log(event.key);
    switch (event.key) {
      case 'Escape':
        setCollapsed(true);
        break;
    }
  }

  return collapsed ? (
    &lt;a href="javascript:;" onClick={()=&gt;setCollapsed(false)}&gt;Search&lt;/a&gt;
  ) : (
    &lt;span&gt;
      &lt;input placeholder="Search" autoFocus /&gt;&amp;nbsp;
      &lt;a href="javascript:;"&gt;This&lt;/a&gt;&amp;nbsp;
      &lt;a href="javascript:;"&gt;That&lt;/a&gt;&amp;nbsp;
      &lt;input placeholder="Refinement" /&gt;
    &lt;/span&gt;
  );
}
ReactDOM.render(&lt;App /&gt;, document.body.appendChild(document.createElement('div')));
</code></pre>

<p>(Live sample at <a href="https://codepen.io/caqu/pen/xBeBMN" rel="noreferrer">https://codepen.io/caqu/pen/xBeBMN</a>)</p>

<p>The problem I see is that the <code>handleKeyUp</code> reference inside <code>removeEventListener</code> is changing every time the component renders. The function <code>handleKeyUp</code> needs a reference to <code>setCollapsed</code> so it must be enclosed by <code>App</code>. Moving <code>handleKeyUp</code> inside <code>useEffect</code> also seems to fire multiple times and lose the reference to the original <code>handleKeyUp</code>.</p>

<p>How can I conditionally window.removeEventListener using React Hooks without unmounting the component?</p>
