React Clearinterval за пределами useFect
/*
If you need to save variables across re-renders use useRef which in this case acts
like a class instance field, also note that mutations to refs does not trigger a
re-render.
This will give you the ability to clear the interval from outside of useEffect
*/
function Child(props) {
let [timerCount, setTimer] = useState(0)
const intervalRef = useRef(null)
useEffect(() => {
intervalRef.current = setInterval(() => {
setTimer(prevState => prevState + 1)
}, 1000)
return () => clearInterval(intervalRef.current)
}, [])
function clearTimer() {
clearInterval(intervalRef.current)
intervalRef.current = null
}
return (
<div>
<div>Timer {timerCount}</div>
<button onClick={clearTimer}>ClearTimer</button>
</div>
)
}
Ugliest Unicorn