Reputation: 458
I will go straight to the point.
I have a variable called showForm const [showForm, setShowForm] =useState(false);
I am controlling if I should show a form or not with it .
The form will also be shown after 20s using setTimeout
and I initialise a timeoutId
(let timeoutId;) variable on global scope to keep track of the setTimeout.
I have a useEffect hook with an if statement that checks the value of showForm
useEffect(()=>{
if(showForm === false){
timeoutId = setTimeout(function () {
setShowForm(true)
}, 13000)
}else{
console.log("timeout cleared",timeoutId)
clearTimeout(timeoutId)
}
},[showForm])
The problem is that even if I change the variable showForm
to true the setTimeout still runs and doesn’t get cleared. the console.log() inside the else runs normally but somehow the setTimeout doesn't get cleared.
I am making a mistake in the logic here? I have spent so many hours that I cant think of the problem anymore...
Upvotes: 0
Views: 78
Reputation: 85545
You have to define the variable with var
, let
or const
in react. Global variable is not allowed:
useEffect(()=>{
let timeoutId
....
return () => clearTimeout(timeouitId)
Returning a function that clears the timeoutId will clear the setTimeout. Note: the timeoutId has to be inside useEffect
Upvotes: 1