El problema: cuando elimino la matriz de dependencias en useEffect el temporizador nunca se detiene. Pero cuando agrego una matriz de dependencias en useEffect el temporizador se atasca en 5 .
¿Como puedo resolver esto?
const App = () => { const [inputValue, setInputValue] = useState(""); const [target, setTarget] = useState([]); const [score, setScore] = useState(0); const [timer, setTimer] = useState(5); const newQuestion = () => { const minimum = 1; const maximum = 10; const int1 = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum; const int2 = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum; setTarget([int1, int2]); }; const handleReset = () => { setScore(0); setTimer(5); }; useEffect(() => { newQuestion(); }, [score]); useEffect(() => { let interval = setInterval(() => { setTimer((prev) => { if (prev === 1) clearInterval(interval); return prev - 1; }); }, 1000); return () => clearInterval(interval); }); const handleAnsewer = () => { const total = target[0] + target[1]; if (total === Number(inputValue)) { setScore(score + 1); } else { if (score > 0) { setScore(score - 1); } } setInputValue(""); newQuestion(); }; return ( <> <h1>Random Math Quiz</h1> <h1> {target.join(" + ")} </h1> <h1> Timer: {timer} </h1> <input placeholder="Answer" value={inputValue} onChange={(e) => setInputValue(e.target.value)} /> <div> <button disabled={timer === 0} onClick={handleAnsewer}> {" "} Submit{" "} </button> </div> <div> <button onClick={handleReset}> play again </button> </div> {score === 10 && <h1> (Score: 10 / {score}) Congrate you are master in Math!</h1>} {score <= 9 && timer < 1 && <h1> ( Score: 10 / {score}) Oh boy this is the math class!</h1>} </> ); }; export default App;Cambie su useEffect que contiene el método setInterval con este:
useEffect(() => { if (timer > 0){ setTimeout(() => {setTimer(timer - 1)}, 1000) } }, [timer]) Creo que el enfoque con setTimeout() es mejor porque no es necesario borrar intervalos ni ninguna de esas tonterías.
setTimer a un nuevo timer - 1 después de 1000mstimer cambia, por lo que activará useEffect y el componente se volverá a procesar0