Last updated: Apr 7, 2024
Reading timeยท2 min
To clear a timeout in React:
useEffect
hook to set up the timeout.useEffect
hook.clearTimeout()
method to clear the timeout when the component
unmounts.import {useEffect, useState} from 'react'; export default function App() { const [isShown, setIsShown] = useState(false); useEffect(() => { const timeoutID = setTimeout(() => { setIsShown(true); }, 1000); return () => { // ๐๏ธ Clear the timeout when the component unmounts clearTimeout(timeoutID); }; }, []); return ( <div> {isShown ? ( <div> <h2>isShown = true</h2> </div> ) : ( <div> <h2>isShown = false</h2> </div> )} </div> ); }
We used the useState hook to keep track of a boolean variable in the state.
const [isShown, setIsShown] = useState(false);
We passed an empty dependencies array to the useEffect hook because we only want to register the timeout once - when the component mounts.
useEffect(() => { const timeoutID = setTimeout(() => { setIsShown(true); }, 1000); return () => { // ๐๏ธ Clear the timeout when the component unmounts clearTimeout(timeoutID); }; }, []);
useEffect
hook multiple times in the same component.We used the
setTimeout()
method in our useEffect
hook to set up a timer that executes a
function after a delay.
The clearTimeout
function is used to clear the timeout, so we can avoid any
memory leaks.
For example, if the component unmounts before the timer expires and we don't clear the timeout, we would have a memory leak.
useEffect
hook is called when the component unmounts.return () => { clearTimeout(timer); };
We used the clearTimeout method to cancel the timeout we previously registered.
If the component unmounts before the delay has expired, the clearTimeout
method runs and clears the timeout.
To clear an interval in React:
useEffect
hook to set up the interval.useEffect
hook.clearInterval()
method to clear the timeout when the component
unmounts.import {useEffect, useState} from 'react'; export default function App() { const [count, setCount] = useState(0); useEffect(() => { const intervalID = setInterval(() => { setCount(prev => prev + 1); }, 1000); // ๐๏ธ Cancel the interval when the component unmounts return () => { clearInterval(intervalID); }; }, []); return ( <div> <h2>Count: {count}</h2> </div> ); }
We used the setInterval() method to repeatedly call a function every N milliseconds.
The
clearInterval
method is used to cancel the timed, repeating action that we set up using
setInterval
.
Clearing the interval is necessary because if our component unmounts, the interval would keep going in the background and would cause a memory leak.
useEffect
hook is called when the component unmounts.return () => { clearInterval(intervalID); };
When the component unmounts, the clearInterval
method clears the interval.
The cleanup step is important because we want to make sure we don't have any memory leaks in our application.