I am currently building a timer component to time how long players take to finish a game from the moment the website loads. If I lift the state of the timer to the parent component, the entire app re-renders every second, rendering my game unresponsive. However I wish to be able to reset the timer from my parent component.
I have moved the state to it’s own component which means that my app isn’t constantly re-rendering, however I am struggling with allowing my parent component reset the timer in my child timer component.
Here is my Timer component – resetTime and setResetTime are a state in the parent component
import { useEffect, useState } from "react";
export default function Timer({
characters,
guessed,
resetTime,
setResetTime,
}) {
const initialTime = 0;
const [runningTime, setRunningTime] = useState(initialTime);
if (resetTime === true) {
setRunningTime(initialTime);
setResetTime(false);
}
useEffect(() => {
const key = setInterval(() => {
if (guessed.length < characters.length) {
setRunningTime((runningTime) => runningTime + 1);
} else {
clearInterval(key);
}
}, 1000);
return () => {
clearInterval(key);
};
}, [characters.length, guessed.length]);
return <h4>{`${runningTime}`}</h4>;
}
And in my parent component I have a button that uses the resetGame() function onClick
function resetGame() {
handleClose();
setGuess(initialGuess);
setGuessed(initialGuessed);
setResetTime(true);
}
<button onClick={resetGame}>Reset Game</button>
This works to reset the timer, however it pops lots of errors in the console about too many re-renders whenever I click it. Further if I click on the reset timer button during the one second interval, it says that I cannot re-render the parent component while a child component is re-rendering, making my button occasionally unresponsive.