# Frontend Refactoring Quick Start Guide ## ๐Ÿš€ What Changed? Your frontend has been refactored to improve maintainability, type safety, and code organization. Here's what you need to know. --- ## ๐Ÿ“ฆ New Shared Utilities ### 1. useLocalStorage Hook **Import:** ```typescript import { useLocalStorage } from '@/hooks'; ``` **Usage:** ```typescript // Instead of managing localStorage manually... const [value, setValue, removeValue] = useLocalStorage('storage-key', defaultValue); // Works just like useState, but persists automatically! setValue({ ...value, updated: true }); ``` **Features:** - Type-safe - Automatic JSON serialization - Error handling built-in - Returns remove function as third element --- ### 2. useApi Hook **Import:** ```typescript import { useApi } from '@/hooks'; ``` **Usage:** ```typescript // Manages loading, error, and data states automatically const { data, loading, error, execute } = useApi( (id: number) => apiService.getData(id), { onSuccess: (data) => console.log('Success!', data), onError: (error) => console.error('Error:', error) } ); // Later in your component... {loading && } {error && {error}} {data && } ``` **Features:** - Automatic request cancellation on unmount - Prevents memory leaks - Consistent loading/error patterns --- ### 3. Formatting Utilities **Import:** ```typescript import { formatCurrency, formatPercent, formatNumber, formatPriceChange } from '@/utils/indicators'; ``` **Usage:** ```typescript // Currency formatting (handles null/undefined) formatCurrency(1234.56) // "$1,234.56" formatCurrency(null) // "โ€”" // Percentage with sign formatPercent(5.25) // "+5.25%" formatPercent(-2.5) // "-2.50%" // Number formatting formatNumber(1234.567) // "1,234.57" // Price change with color const { text, color } = formatPriceChange(5.25); // { text: "+5.25", color: "text-green-400" } ``` **Replace these patterns:** ```typescript // โŒ Old way const formatNumber = (value?: number | null) => { if (value === undefined || value === null) return 'โ€”'; return new Intl.NumberFormat('en-US', { maximumFractionDigits: 2 }).format(value); }; // โœ… New way import { formatNumber } from '@/utils/indicators'; ``` --- ### 4. Modal Components **Import:** ```typescript import { Modal, ConfirmModal, AlertModal } from '@/components/shared/Modal'; ``` **Replace `confirm()`:** ```typescript // โŒ Old way if (confirm('Are you sure you want to delete this?')) { handleDelete(); } // โœ… New way const [showConfirm, setShowConfirm] = useState(false); setShowConfirm(false)} onConfirm={handleDelete} title="Delete Item" message="Are you sure you want to delete this?" variant="danger" /> ``` **Replace `alert()`:** ```typescript // โŒ Old way alert('Success! Your changes have been saved.'); // โœ… New way const [showAlert, setShowAlert] = useState(false); setShowAlert(false)} title="Success" message="Your changes have been saved." variant="success" /> ``` **Custom Modal:** ```typescript setOpen(false)} title="Custom Dialog" size="lg">

Your custom content here

``` **Modal Props:** - `size`: 'sm' | 'md' | 'lg' | 'xl' - `showCloseButton`: boolean (default: true) - `closeOnEscape`: boolean (default: true) - `closeOnBackdropClick`: boolean (default: true) --- ## ๐Ÿ—๏ธ New Component Structure ### DailyTradingPlan Refactored **Location changed:** ```typescript // โŒ Old import import DailyTradingPlan from './components/DailyTradingPlan'; // โœ… New import import DailyTradingPlan from './components/features/trading/DailyTradingPlan'; ``` **Props unchanged** - no breaking changes! **Internal structure:** ``` DailyTradingPlan/ โ”œโ”€โ”€ index.tsx # Main container โ”œโ”€โ”€ types.ts # TypeScript interfaces โ”œโ”€โ”€ usePlanGeneration.ts # AI logic hook โ”œโ”€โ”€ PlanHeader.tsx # Sub-component โ”œโ”€โ”€ PlanBiasSelector.tsx # Sub-component โ”œโ”€โ”€ PlanRiskParameters.tsx # Sub-component โ””โ”€โ”€ PlanKeyLevelsEditor.tsx # Sub-component ``` --- ## ๐ŸŽจ Patterns to Follow ### 1. Component Organization ``` components/ โ”œโ”€โ”€ features/ # Feature-specific components โ”‚ โ”œโ”€โ”€ trading/ โ”‚ โ”œโ”€โ”€ analytics/ โ”‚ โ”œโ”€โ”€ ai/ โ”‚ โ””โ”€โ”€ journal/ โ”œโ”€โ”€ shared/ # Reusable UI components โ”‚ โ”œโ”€โ”€ Modal.tsx โ”‚ โ”œโ”€โ”€ Button.tsx โ”‚ โ””โ”€โ”€ Input.tsx โ””โ”€โ”€ layout/ # Layout components โ””โ”€โ”€ DashboardLayout.tsx ``` ### 2. Component File Structure For complex components, create a directory: ``` MyComponent/ โ”œโ”€โ”€ index.tsx # Main container โ”œโ”€โ”€ types.ts # TypeScript interfaces โ”œโ”€โ”€ useMyLogic.ts # Custom hooks โ”œโ”€โ”€ SubComponentA.tsx # Sub-component โ””โ”€โ”€ SubComponentB.tsx # Sub-component ``` Export from `index.tsx`: ```typescript export default function MyComponent() { ... } export type { MyComponentProps } from './types'; ``` ### 3. Custom Hooks Pattern ```typescript // useMyFeature.ts import { useState, useCallback } from 'react'; export interface UseMyFeatureReturn { data: MyData | null; loading: boolean; error: string | null; execute: () => Promise; reset: () => void; } export function useMyFeature(): UseMyFeatureReturn { const [data, setData] = useState(null); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const execute = useCallback(async () => { setLoading(true); setError(null); try { const result = await fetchData(); setData(result); } catch (err) { setError(err instanceof Error ? err.message : 'Unknown error'); } finally { setLoading(false); } }, []); const reset = useCallback(() => { setData(null); setError(null); }, []); return { data, loading, error, execute, reset }; } ``` ### 4. TypeScript Best Practices ```typescript // โœ… Do: Explicit interfaces interface MyComponentProps { value: number; onChange: (value: number) => void; label?: string; } // โœ… Do: Explicit return types function MyComponent({ value, onChange, label }: MyComponentProps): JSX.Element { const handleChange = useCallback((newValue: number): void => { onChange(newValue); }, [onChange]); return
...
; } // โŒ Don't: Use 'any' const [data, setData] = useState(null); // Bad! // โœ… Do: Use proper types interface MyData { id: number; name: string; } const [data, setData] = useState(null); // Good! ``` --- ## ๐Ÿ”ง Migration Checklist When refactoring a component: - [ ] Move to appropriate feature directory - [ ] Extract types to `types.ts` - [ ] Extract business logic to custom hooks - [ ] Split into sub-components (if > 250 lines) - [ ] Replace `localStorage` patterns with `useLocalStorage` - [ ] Replace direct API calls with `useApi` - [ ] Replace `alert`/`confirm` with Modal components - [ ] Use formatting utilities from `@/utils/indicators` - [ ] Remove all `any` types - [ ] Add explicit return types - [ ] Wrap callbacks in `useCallback` - [ ] Wrap expensive calculations in `useMemo` - [ ] Add ARIA attributes for accessibility - [ ] Update imports in parent components --- ## ๐Ÿงช Testing Your Changes ### Quick Smoke Test: ```bash cd frontend npm run build ``` Should compile without TypeScript errors! ### Runtime Test: ```bash npm run dev ``` Check: 1. Component loads without errors 2. State updates work 3. localStorage persists 4. Modals open/close correctly 5. No console warnings --- ## ๐Ÿ“š Additional Resources - [React Hooks Documentation](https://react.dev/reference/react) - [TypeScript Handbook](https://www.typescriptlang.org/docs/) - [ARIA Authoring Practices](https://www.w3.org/WAI/ARIA/apg/) --- ## โ“ FAQ **Q: Can I still use the old DailyTradingPlan import?** A: No, update imports to the new location. The old file will be removed. **Q: Do I need to refactor all components at once?** A: No! Refactor incrementally. Start with components you're actively working on. **Q: What if I need localStorage outside a component?** A: Create a separate utility function or use the hook in the nearest parent component. **Q: Should I use ConfirmModal for every confirmation?** A: Yes! It provides better UX and accessibility than native `confirm()`. **Q: Can I customize Modal appearance?** A: Yes! The Modal component uses Tailwind classes. Extend or override as needed. --- ## ๐Ÿ†˜ Getting Help If you encounter issues: 1. Check TypeScript errors in your IDE 2. Review the summary document: `WEEK1_2_REFACTORING_SUMMARY.md` 3. Look at refactored DailyTradingPlan as an example 4. Ask the team! --- **Last Updated:** Week 1-2 Refactoring **Next Update:** Week 3-4 (TradingJournal & AITradingCoach refactoring)