title: How to use an `onClick` event to stop calling a function which is called by the useEffect hook?
body: <p>How to use an <code>onClick</code> event to stop a recurring function call? The function call is recurring due to using <code>useEffect</code>, <code>setInterval</code> and <code>clearInterval</code>.</p>
  
  <p>An example shown in <a href="https://upmostly.com/tutorials/setinterval-in-react-components-using-hooks" rel="nofollow noreferrer">this article</a>, the below code will run forever. How to stop the function from being called once the <code>&lt;header&gt;&lt;/header&gt;</code> is clicked?</p>
  
  <pre><code>import React, { useState, useEffect } from 'react';
  
  const IntervalExample = () =&gt; {
    const [seconds, setSeconds] = useState(0);
  
    useEffect(() =&gt; {
      const interval = setInterval(() =&gt; {
        setSeconds(seconds =&gt; seconds + 1);
      }, 1000);
      return () =&gt; clearInterval(interval);
    }, []);
  
    return (
      &lt;div className="App"&gt;
        &lt;header className="App-header"&gt;
          {seconds} seconds have elapsed since mounting.
        &lt;/header&gt;
      &lt;/div&gt;
    );
  };
  
  export default IntervalExample;
  </code></pre>