title: React: Keypress listener on div
body: <p>I'm currently having trouble creating a keypress listener (or any listener) on a component.</p>
  <p>Essentially I would like to have my listener triggered whenever I press &quot;ESC&quot;, but I'm finding myself blocked.</p>
  <p>My function component is pretty simple, it looks like this:</p>
  <pre><code>
  const Component = () =&gt; {
    useEffect(() =&gt; {
      const handler = (e: KeyboardEvent) =&gt; {
        if (e.isComposing || e.keyCode === 27) {
          console.log('do something');
        }
      };
  
      window.addEventListener('keydown', handler, false);
      return () =&gt; window.removeEventListener('keydown', handler, false);
    }, []);
  
    return &lt;div /&gt;;
  };
  </code></pre>
  <p>When my component is mounted, the <code>window</code> listener is correctly added. Unfortunately after the component unmounts, the event listener is not removed.</p>
  <p>So I tried adding the event listener specifically to the div I'm mounting:</p>
  <pre><code>
  const Component = () =&gt; {
    const ref = useRef(null);
    useEffect(() =&gt; {
      const handler = (e: KeyboardEvent) =&gt; {
        if (e.isComposing || e.keyCode === 27) {
          console.log('do something');
        }
      };
  
      const divRef = ref.current as any;
  
      divRef.addEventListener('keydown', handler, false);
      return () =&gt; divRef.removeEventListener('keydown', handler, false);
    }, []);
  
    return &lt;div ref={ref} /&gt;;
  };
  </code></pre>
  <p>But this just doesn't work at all and the handler is never called.</p>