I am trying to access clearTimerInterval
in clearTimer
method but getting undefined , got the waring variable from inside React Hook will be lost after each render
. in below code useEffect
hook called once once then how variable clearTimerInterval
got undefined?
function Child(props) {
let [timerCount, setTimer] = useState(0);
var clearTimerInterval;
useEffect(() => {
clearTimerInterval = setInterval(() => {
setTimer(timerCount => {
return timerCount + 1;
});
}, 1000);
return () => {
clearInterval(clearTimerInterval);
};
}, []);
function clearTimer() {
clearInterval(clearTimerInterval);
}
return (
<div>
<div>Timer {timer}</div>
<button onClick={clearTimer}>ClearTimer</button>
</div>
);
}
export default React.memo(Child);
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>
)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With