title: React TypeScript How to attach an event listener to window.matchMedia
body: <p>When the react page loads it detects if the user has set dark mode in their operating system </p>
  
  <pre><code>const darkMode = window.matchMedia('(prefers-color-scheme: dark)').matches;
  </code></pre>
  
  <p>and then renders one of two images depending on the result</p>
  
  <pre><code>import logoDark from '../images/logoDark.svg';
  import logoLight from '../images/logoLight.svg';
  
  &lt;img src={darkMode ? logoDark : logoLight} /&gt;
  </code></pre>
  
  <p>But if the user changes mode after the page has loaded the image isn't updated, how do I add an event listener to window.matchMedia ? </p>
  
  <p>I have tried with..</p>
  
  <pre><code>  darkMode.addEventListener( "change", (e) =&gt; {
      darkMode = e.matches;
      console.log(e.matches) // true / false
    });
  </code></pre>
  
  <p>but I get the error <code>Type 'boolean' is not assignable to type 'MediaQueryList'.ts(2322)</code></p>
  
  <p><strong>UDATE</strong>: Working Code</p>
  
  <pre><code>import React, {useContext} from "react";
  import Context from '../components/context';
  import logoDark from '../images/logoDark.svg';
  import logoLight from '../images/logoLight.svg';
  
  const Home: React.FC = () =&gt; {
    const darkMode = window.matchMedia('(prefers-color-scheme: dark)');   
    darkMode.addEventListener( "change", (e) =&gt; {
      if (e.matches) {
        setGlobal({...global, mode: true})
      } else {
        setGlobal({...global, mode: false})
      }
    });
    return (
    &lt;img src={global.mode ? logoDark : logoLight} /&gt;
  }
  
  export default Home;
  </code></pre>