Skip to content
Shell
2.6 KB
Raw Blame

Fix React Hooks Rules Violation in ScalarMarketCard

Problem Analysis

Location: /Users/eddiebelaval/Development/deepstack/web/src/components/prediction-markets/ScalarMarketCard.tsx:85

Issue: useEffect hook is called after a conditional early return (line 55), violating React's Rules of Hooks.

// Lines 52-56
const bounds = market.scalarBounds;
if (!bounds) {
  return null; // ← Early return
}

// Lines 85-110
useEffect(() => { ... }); // ← Hook called AFTER early return - VIOLATION

Solution: Move Early Return After All Hooks

Approach: Refactor so all hooks are called at the top level, before any conditional returns.

Changes Required:

  1. Move state declarations (already at top - OK)

    • useState hooks at lines 49-50 are correctly positioned
  2. Move useEffect hook before the early return

    • Position useEffect immediately after state declarations
    • Make the effect conditional internally to handle missing bounds gracefully
  3. Keep early return logic but move it AFTER all hooks

    • Check !bounds and return null AFTER the useEffect

Refactored Structure:

export function ScalarMarketCard({ ... }) {
  // 1. All state hooks first (already correct)
  const [priceHistory, setPriceHistory] = useState<MarketPricePoint[]>([]);
  const [isLoadingHistory, setIsLoadingHistory] = useState(false);

  // 2. All effect hooks next (MOVE HERE)
  useEffect(() => {
    // Make loading conditional on bounds existence
    if (!market.scalarBounds) return;

    const loadHistory = async () => { ... };
    loadHistory();
  }, [market.platform, market.id, market.yesPrice, market.title, market.scalarBounds]);

  // 3. Early returns AFTER all hooks (MOVE HERE)
  const bounds = market.scalarBounds;
  if (!bounds) {
    return null;
  }

  // 4. Rest of component logic
  const outcomes = market.outcomes || [];
  // ...
}

Verification Steps:

  1. Ensure all hooks are called before any conditional returns
  2. Add market.scalarBounds to effect dependencies to prevent stale closures
  3. Add internal guard in effect to skip loading when bounds don't exist
  4. Test that component still renders correctly for both scalar markets (with bounds) and edge cases (without bounds)

Files to Edit:

  • /Users/eddiebelaval/Development/deepstack/web/src/components/prediction-markets/ScalarMarketCard.tsx

Branch Created:

  • feature/fix-scalar-market-hooks-violation

Confidence Level: HIGH

This is a standard React Hooks refactoring pattern. The fix moves all hook calls to the top level before any conditional logic, which is the canonical solution for Rules of Hooks violations.