How to use an onClick
event to stop a recurring function call? The function call is recurring due to using useEffect
, setInterval
and clearInterval
.
An example shown in this article, the below code will run forever. How to stop the function from being called once the <header></header>
is clicked?
import React, { useState, useEffect } from 'react';
const IntervalExample = () => {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setSeconds(seconds => seconds + 1);
}, 1000);
return () => clearInterval(interval);
}, []);
return (
<div className="App">
<header className="App-header">
{seconds} seconds have elapsed since mounting.
</header>
</div>
);
};
export default IntervalExample;