Skip to content

🐛 Potential Memory Leak in useMarkets Auto-Refresh #43

@Mosas2000

Description

@Mosas2000

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

  1. Use setTimeout instead of setInterval to prevent overlap
  2. Check document.visibilityState to pause when tab is hidden
  3. Add abort controller for in-flight requests on unmount
  4. Consider using React Query for better cache management

Files Affected

  • frontend/src/hooks/useMarkets.ts

Priority

🟡 Medium - Can cause subtle bugs

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions