title: Setting an interval on a click event in React using Hooks won't use updated state values
body: <p>I am trying to create a filter dropdown menu that hides itself if the user did not close it manually and has moved their mouse away from the filter after 1 second.</p>
  <p>The problem is that the <code>mouseInside</code> boolean state never gets changed to <code>false</code> inside the interval. I believe this is because the react component gets re-rendered but not entirely sure.</p>
  <p>I don't know how to fix it or how I might be using state vs local variables incorrectly.</p>
  <p>I'm using TypeScript in React with hooks:</p>
  <pre><code>const Filter: React.FC = () =&gt; {
    const [shown, setShown] = useState&lt;boolean&gt;(false);
    const [mouseInside, setMouseInside] = useState&lt;boolean&gt;(false);
    
    let interval: NodeJS.Timeout | null = null;
  
    const handleToggle = () =&gt; {
        setShown(!shown);
        
        interval = setInterval(() =&gt; {
          console.log(mouseInside);
  
          // mouseInside is permanently true
          if (!mouseInside &amp;&amp; interval) {
             // this never gets triggered
             clearInterval(interval);
             setShown(false);
             console.log(&quot;Finished!&quot;);
          }
        }, 1000);
      }
    };
  
    return (
      &lt;div
        style={{ width: 100, height: 100, backgroundColor: &quot;lightgray&quot; }}  
        onClick={handleToggle}
        onMouseEnter={() =&gt; setMouseInside(true)}
        onMouseLeave={() =&gt; setMouseInside(false)}
      &gt;
          &lt;p&gt;Click me!&lt;/p&gt;
          
          {shown &amp;&amp; &lt;div&gt;drop down here...&lt;/dv&gt;}
      &lt;/div&gt;
      );
  };
  </code></pre>
  <p>I need mouseInside to eventually change to false when the user leaves the filter box. The <code>onMouseLeave</code> event is definitely being triggered but it's the React side of things I think is causing the issue.</p>
  <p>Maybe I need to use <code>useEffect</code>? I don't know the best approach though on how to use this with <code>setInterval</code>.</p>