-
Notifications
You must be signed in to change notification settings - Fork 1
🐛 Potential Memory Leak in useMarkets Auto-Refresh #43
Copy link
Copy link
Closed
Labels
bugSomething isn't workingSomething isn't working
Description
Description
The useMarkets hook sets up an interval for auto-refreshing but could cause memory leaks or race conditions.
Current Implementation
// useMarkets.ts (Lines 73-84)
useEffect(() => {
fetchMarkets();
// Auto-refresh every 30 seconds
intervalRef.current = setInterval(fetchMarkets, 30000);
return () => {
if (intervalRef.current) {
clearInterval(intervalRef.current);
}
};
}, [fetchMarkets]);Potential Issues
1. Race Conditions
If fetchMarkets takes longer than 30 seconds, multiple requests could overlap and update state out of order.
2. Unnecessary Requests
Continues fetching even when tab is not visible, wasting resources and API calls.
3. State Update After Unmount
If the component unmounts during a fetch, state update could be attempted on unmounted component.
Suggested Fix
useEffect(() => {
let isMounted = true;
let timeoutId: NodeJS.Timeout;
const fetchWithDelay = async () => {
await fetchMarkets();
// Only schedule next fetch if still mounted
if (isMounted && document.visibilityState === 'visible') {
timeoutId = setTimeout(fetchWithDelay, 30000);
}
};
// Listen for visibility changes
const handleVisibility = () => {
if (document.visibilityState === 'visible') {
fetchWithDelay();
}
};
document.addEventListener('visibilitychange', handleVisibility);
fetchWithDelay();
return () => {
isMounted = false;
clearTimeout(timeoutId);
document.removeEventListener('visibilitychange', handleVisibility);
};
}, [fetchMarkets]);Improvements
- Use
setTimeoutinstead ofsetIntervalto prevent overlap - Check
document.visibilityStateto pause when tab is hidden - Add abort controller for in-flight requests on unmount
- Consider using React Query for better cache management
Files Affected
frontend/src/hooks/useMarkets.ts
Priority
🟡 Medium - Can cause subtle bugs
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
bugSomething isn't workingSomething isn't working