title: how do I clearInterval on-click, with React Hooks?
body: <p>I'm trying to refactor my code to react hooks, but I'm not sure if i'm doing it correctly.  I tried copying and pasting my setInterval/setTimout code into hooks, but it did not work as intended.  After trying different things I was able to get it to work, but I'm not sure if this is the best way to do it.</p>
  
  <p>I know i can use useEffect to clear interval on un-mount, but I want to clear it before un-mounting.</p>
  
  <p>Is the following good practice and if not what is a better way of clearing setInterval/setTimout  before un-mounting?</p>
  
  <p>Thanks,</p>
  
  <p><strong>useTimeout</strong></p>
  
  <pre><code>import { useState, useEffect } from 'react';
  
  let timer = null;
  
  const useTimeout = () =&gt; {
      const [count, setCount] = useState(0);
      const [timerOn, setTimerOn] = useState(false);
  
      useEffect(() =&gt; {
          if (timerOn) {
              console.log("timerOn ", timerOn);
  
              timer = setInterval(() =&gt; {
                  setCount((prev) =&gt; prev + 1)
              }, 1000);
  
          } else {
              console.log("timerOn ", timerOn);
              clearInterval(timer);
              setCount(0);
          }
      return () =&gt; {
          clearInterval(timer);
      }
      }, [timerOn])
  
      return [count, setCount, setTimerOn];
  }
  
  export default useTimeout;
  </code></pre>
  
  <p><strong>Component</strong></p>
  
  <pre><code>import React from 'react';
  import useTimeout from './useTimeout';
  
  const UseStateExample = () =&gt; {
      const [count, setCount, setTimerOn] = useTimeout()
      return (
          &lt;div&gt;
              &lt;h2&gt;Notes:&lt;/h2&gt;
              &lt;p&gt;New function are created on each render&lt;/p&gt;
              &lt;br /&gt;
              &lt;h2&gt;count = {count}&lt;/h2&gt;
              &lt;button onClick={() =&gt; setCount(prev =&gt; prev + 1)}&gt;Increment&lt;/button&gt;
              &lt;br /&gt;
              &lt;button onClick={() =&gt; setCount(prev =&gt; prev - 1)}&gt;Decrement&lt;/button&gt;
              &lt;br /&gt;
              &lt;button onClick={() =&gt; setTimerOn(true)}&gt;Set Interval&lt;/button&gt;
              &lt;br /&gt;
              &lt;button onClick={() =&gt; setTimerOn(false)}&gt;Stop Interval&lt;/button&gt;
              &lt;br /&gt;
  
          &lt;/div&gt;
      );
  }
  
  export default UseStateExample;
  </code></pre>