0 day streak
javascript / beginner
Snippet

Managing Asynchronous Timers and Cleanup with useEffect

Asynchronous tasks like setTimeout inside useEffect must be paired with a cleanup function. Returning a cleanup function prevents memory leaks and stale state updates if the component unmounts before the timer finishes.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import React, { useState, useEffect } from 'react';
function DelayedNotice() {
const [isVisible, setIsVisible] = useState(false);
useEffect(() => {
const timerId = setTimeout(() => {
setIsVisible(true);
}, 3000);
return () => clearTimeout(timerId);
}, []);
return <div>{isVisible && <p>Notice: Session active!</p>}</div>;
}
export default DelayedNotice;
react
Breakdown
1
const timerId = setTimeout(() => { setIsVisible(true); }, 3000);
Schedules an asynchronous state update to run after 3000 milliseconds.
2
return () => clearTimeout(timerId);
Returns a cleanup function to cancel the pending timer if the component unmounts.
3
}, []);
Passes an empty dependency array so the effect runs only once after the initial render.