I have the following problem with the useInterval hook, Im trying to make the counter stop if it hits count 20, but it seems that the way im currently implementing it it seems to cause infinite loop of render. here is my code so far:
import React, { ChangeEvent, useState } from "react";
import { useInterval } from "usehooks-ts";
export default function Component() {
// The counter
const [count, setCount] = useState<number>(0);
// Dynamic delay
const [delay, setDelay] = useState<number>(1000);
// ON/OFF
const [isPlaying, setPlaying] = useState<boolean>(true);
useInterval(
() => {
// Your custom logic here
setCount(count + 1);
},
// Delay in milliseconds or null to stop it
isPlaying ? delay : null
);
if (count === 10) {
setPlaying(false);
}
const handleChange = (event: ChangeEvent<HTMLInputElement>) => {
setDelay(Number(event.target.value));
};
return (
<>
<h1>{count}</h1>
<button onClick={() => setPlaying(!isPlaying)}>
{isPlaying ? "pause" : "play"}
</button>
<p>
<label htmlFor="delay">Delay: </label>
<input
type="number"
name="delay"
onChange={handleChange}
value={delay}
/>
</p>
</>
);
}
I can't grasp on why this wont work, could someone explain and show me what im doing wrong?