Learn how useEffect manages side effects, event listeners, timers, and API calls!
Auto-increment: ON
Speed: 1000ms
Initial Counter: 0
Window Size: ON
Mouse Position: ON
Keyboard: ON
Auto-fetch: ON
API Delay: 2000ms
Max Attempts: 3
Started at: 0 | Auto-increment: 1000ms
No fetch initiated
Auto-fetch: ON
Delay: 2000ms
Attempts: 0/3
Success Rate: ~70%
useEffect(() => {
const timer = setInterval(() => {
setCounter(prev => prev + 1);
}, 1000);
// Cleanup function - VERY IMPORTANT!
return () => {
clearInterval(timer);
};
}, [1000]); // Re-run when speed changesAlways clean up timers, intervals, and subscriptions to prevent memory leaks.
useEffect(() => {
if (!true) return; // Early return
const handleMouseMove = (e) => {
setMousePosition({ x: e.clientX, y: e.clientY });
};
window.addEventListener('mousemove', handleMouseMove);
return () => {
window.removeEventListener('mousemove', handleMouseMove);
};
}, [true]);Add event listeners in useEffect and remove them in cleanup function.
useEffect(() => {
if (!shouldFetchData) return;
const fetchData = async () => {
setLoading(true);
try {
const response = await fetch('/api/data');
const data = await response.json();
setData(data);
} catch (error) {
setError(error.message);
} finally {
setLoading(false);
}
};
fetchData();
}, [shouldFetchData, apiUrl]); // Re-fetch when these changeUse async functions inside useEffect for API calls. Handle loading and error states.
enableAutoIncrement = false - watch timer stop!autoIncrementSpeed to 500ms - see faster countingtrackMousePosition and move your mouseapiDelay to 5000ms - watch the loading take longermaxFetchAttempts = 1 to see fewer retries