optimize boot sequnse

This commit is contained in:
hansoo
2025-03-19 07:27:10 +09:00
parent ab3bcbdc63
commit 2ec913c6c0
12 changed files with 224 additions and 180 deletions

View File

@@ -22,7 +22,7 @@ import Settings from './pages/Settings';
import { BudgetProvider } from './contexts/BudgetContext'; import { BudgetProvider } from './contexts/BudgetContext';
import PrivateRoute from './components/auth/PrivateRoute'; import PrivateRoute from './components/auth/PrivateRoute';
// 전역 오류 핸들러 // 전역 오류 핸들러
const handleError = (error: any) => { const handleError = (error: Error | unknown) => {
console.error('앱 오류 발생:', error); console.error('앱 오류 발생:', error);
}; };
@@ -77,7 +77,7 @@ function App() {
// 웹뷰 콘텐츠가 완전히 로드되었을 때만 스플래시 화면을 숨김 // 웹뷰 콘텐츠가 완전히 로드되었을 때만 스플래시 화면을 숨김
const onAppReady = async () => { const onAppReady = async () => {
try { try {
// 1초 후에 스플래시 화면을 숨김 (콘텐츠가 완전히 로드될 시간 확보) // 스플래시 화면을 더 빠르게 숨김 (데이터 로딩과 별도로 진행)
setTimeout(async () => { setTimeout(async () => {
try { try {
await SplashScreen.hide(); await SplashScreen.hide();
@@ -85,7 +85,7 @@ function App() {
} catch (err) { } catch (err) {
console.error('스플래시 화면 숨김 오류:', err); console.error('스플래시 화면 숨김 오류:', err);
} }
}, 1000); }, 500); // 500ms로 줄임
} catch (err) { } catch (err) {
console.error('앱 준비 오류:', err); console.error('앱 준비 오류:', err);
} }
@@ -96,9 +96,13 @@ function App() {
// 추가 보호장치: 페이지 로드 시 다시 실행 // 추가 보호장치: 페이지 로드 시 다시 실행
const handleLoad = () => { const handleLoad = () => {
// 즉시 스플래시 화면을 숨김 시도
SplashScreen.hide().catch(() => {});
// 백업 시도
setTimeout(() => { setTimeout(() => {
SplashScreen.hide().catch(() => {}); SplashScreen.hide().catch(() => {});
}, 1000); }, 300);
}; };
window.addEventListener('load', handleLoad); window.addEventListener('load', handleLoad);

View File

@@ -2,7 +2,7 @@
import React, { useState } from 'react'; import React, { useState } from 'react';
import { Trash2 } from 'lucide-react'; import { Trash2 } from 'lucide-react';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { useAuth } from '@/contexts/auth/AuthProvider'; import { useAuth } from '@/contexts/auth';
import { useDataReset } from '@/hooks/useDataReset'; import { useDataReset } from '@/hooks/useDataReset';
import DataResetDialog from './DataResetDialog'; import DataResetDialog from './DataResetDialog';
import { isSyncEnabled } from '@/utils/sync/syncSettings'; import { isSyncEnabled } from '@/utils/sync/syncSettings';

View File

@@ -1,6 +1,7 @@
import React from 'react'; import React from 'react';
import { AuthProvider, useAuth } from './auth/AuthProvider'; import { AuthProvider } from './auth/AuthProvider';
import { useAuth } from './auth/useAuth';
export { AuthProvider, useAuth }; export { AuthProvider, useAuth };

View File

@@ -1,13 +1,12 @@
import React, { createContext, useContext, useEffect, useState } from 'react'; import React, { useEffect, useState } from 'react';
import { supabase } from '@/lib/supabase'; import { supabase } from '@/lib/supabase';
import { Session, User } from '@supabase/supabase-js'; import { Session, User } from '@supabase/supabase-js';
import { toast } from '@/hooks/useToast.wrapper'; import { toast } from '@/hooks/useToast.wrapper';
import { AuthContextType } from './types'; import { AuthContextType } from './types';
import * as authActions from './authActions'; import * as authActions from './authActions';
import { clearAllToasts } from '@/hooks/toast/toastManager'; import { clearAllToasts } from '@/hooks/toast/toastManager';
import { AuthContext } from './useAuth';
const AuthContext = createContext<AuthContextType | undefined>(undefined);
export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => { export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const [session, setSession] = useState<Session | null>(null); const [session, setSession] = useState<Session | null>(null);
@@ -15,35 +14,60 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
useEffect(() => { useEffect(() => {
// 현재 세션 체크 // 현재 세션 체크 - 최적화된 버전
const getSession = async () => { const getSession = async () => {
try { try {
console.log('세션 로딩 시작');
// 비동기 작업을 마이크로태스크로 지연하여 UI 차단 방지
await new Promise<void>(resolve => queueMicrotask(() => resolve()));
const { data, error } = await supabase.auth.getSession(); const { data, error } = await supabase.auth.getSession();
if (error) { if (error) {
console.error('세션 로딩 중 오류:', error); console.error('세션 로딩 중 오류:', error);
} else if (data.session) { } else if (data.session) {
// 상태 업데이트를 마이크로태스크로 지연
queueMicrotask(() => {
setSession(data.session); setSession(data.session);
setUser(data.session.user); setUser(data.session.user);
console.log('세션 로딩 완료');
});
} else {
console.log('활성 세션 없음');
} }
} catch (error) { } catch (error) {
console.error('세션 확인 중 예외 발생:', error); console.error('세션 확인 중 예외 발생:', error);
} finally { } finally {
// 로딩 상태 업데이트를 마이크로태스크로 지연
queueMicrotask(() => {
setLoading(false); setLoading(false);
});
} }
}; };
// 초기 세션 로딩 - 약간 지연시켜 UI 렌더링 우선시
setTimeout(() => {
getSession(); getSession();
}, 100);
// auth 상태 변경 리스너 // auth 상태 변경 리스너 - 최적화된 버전
const { data: { subscription } } = supabase.auth.onAuthStateChange( const { data: { subscription } } = supabase.auth.onAuthStateChange(
async (event, session) => { async (event, session) => {
console.log('Supabase auth 이벤트:', event); console.log('Supabase auth 이벤트:', event);
// 비동기 작업을 마이크로태스크로 지연하여 UI 차단 방지
await new Promise<void>(resolve => queueMicrotask(() => resolve()));
if (session) { if (session) {
// 상태 업데이트를 마이크로태스크로 지연
queueMicrotask(() => {
setSession(session); setSession(session);
setUser(session.user); setUser(session.user);
});
} else if (event === 'SIGNED_OUT') { } else if (event === 'SIGNED_OUT') {
// 상태 업데이트를 마이크로태스크로 지연
queueMicrotask(() => {
setSession(null); setSession(null);
setUser(null); setUser(null);
@@ -52,9 +76,13 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
// 로그아웃 이벤트 발생시켜 SyncSettings 등에서 감지하도록 함 // 로그아웃 이벤트 발생시켜 SyncSettings 등에서 감지하도록 함
window.dispatchEvent(new Event('auth-state-changed')); window.dispatchEvent(new Event('auth-state-changed'));
});
} }
// 로딩 상태 업데이트를 마이크로태스크로 지연
queueMicrotask(() => {
setLoading(false); setLoading(false);
});
} }
); );
@@ -78,10 +106,4 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>; return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}; };
export const useAuth = () => { // useAuth 후크는 useAuth.ts 파일로 이동했습니다
const context = useContext(AuthContext);
if (context === undefined) {
throw new Error('useAuth는 AuthProvider 내부에서 사용해야 합니다');
}
return context;
};

View File

@@ -1,3 +1,4 @@
export { AuthProvider, useAuth } from './AuthProvider'; export { AuthProvider } from './AuthProvider';
export { useAuth } from './useAuth';
export type { AuthContextType } from './types'; export type { AuthContextType } from './types';

View File

@@ -0,0 +1,17 @@
import { useContext, createContext } from 'react';
import { AuthContextType } from './types';
// AuthContext 생성
export const AuthContext = createContext<AuthContextType | undefined>(undefined);
/**
* 인증 컨텍스트에 접근하기 위한 커스텀 훅
* AuthProvider 내부에서만 사용해야 함
*/
export const useAuth = () => {
const context = useContext(AuthContext);
if (context === undefined) {
throw new Error('useAuth는 AuthProvider 내부에서 사용해야 합니다');
}
return context;
};

View File

@@ -1,29 +1,8 @@
import React, { createContext, useContext } from 'react'; import React from 'react';
import { useBudgetState } from './useBudgetState'; import { useBudgetState } from './useBudgetState';
import { BudgetData, BudgetPeriod, Transaction } from './types'; import { BudgetContext, BudgetContextType } from './useBudget';
import { BudgetPeriod } from './types';
// 컨텍스트 인터페이스 정의
interface BudgetContextType {
transactions: Transaction[];
selectedTab: BudgetPeriod;
setSelectedTab: (tab: BudgetPeriod) => void;
budgetData: BudgetData;
categoryBudgets: Record<string, number>;
getCategorySpending: () => Array<{
title: string;
current: number;
total: number;
}>;
addTransaction: (transaction: Transaction) => void;
updateTransaction: (transaction: Transaction) => void;
deleteTransaction: (id: string) => void;
handleBudgetGoalUpdate: (type: BudgetPeriod, amount: number, newCategoryBudgets?: Record<string, number>) => void;
resetBudgetData?: () => void; // 선택적 필드로 추가
}
// 컨텍스트 생성
const BudgetContext = createContext<BudgetContextType | undefined>(undefined);
// 컨텍스트 프로바이더 컴포넌트 // 컨텍스트 프로바이더 컴포넌트
export const BudgetProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => { export const BudgetProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
@@ -36,13 +15,7 @@ export const BudgetProvider: React.FC<{ children: React.ReactNode }> = ({ childr
); );
}; };
// 훅을 통한 컨텍스트 접근 // useBudget 훅은 useBudget.ts 파일로 이동했습니다
export const useBudget = (): BudgetContextType => { export { useBudget, BudgetContextType } from './useBudget';
const context = useContext(BudgetContext);
if (context === undefined) {
throw new Error('useBudget must be used within a BudgetProvider');
}
return context;
};
export type { BudgetPeriod } from './types'; export type { BudgetPeriod } from './types';

View File

@@ -12,79 +12,60 @@ import {
calculateSpentAmounts calculateSpentAmounts
} from '../budgetUtils'; } from '../budgetUtils';
import { Transaction } from '../types';
// 예산 데이터 상태 관리 훅 // 예산 데이터 상태 관리 훅
export const useBudgetDataState = (transactions: any[]) => { export const useBudgetDataState = (transactions: Transaction[]) => {
const [budgetData, setBudgetData] = useState<BudgetData>(loadBudgetDataFromStorage()); const [budgetData, setBudgetData] = useState<BudgetData>(loadBudgetDataFromStorage());
const [selectedTab, setSelectedTab] = useState<BudgetPeriod>("daily"); const [selectedTab, setSelectedTab] = useState<BudgetPeriod>("daily");
const [isInitialized, setIsInitialized] = useState(false); const [isInitialized, setIsInitialized] = useState(false);
// 초기 로드 및 이벤트 리스너 설정 // 초기 로드 및 이벤트 리스너 설정 - 최적화된 버전
useEffect(() => { useEffect(() => {
const loadBudget = () => { // 예산 데이터 로드 함수 - 비동기 처리로 변경
const loadBudget = async () => {
try { try {
console.log('예산 데이터 로드 시도 중...'); console.log('예산 데이터 로드 시도 중...');
// 비동기 작업을 마이크로태스크로 지연
await new Promise<void>(resolve => queueMicrotask(() => resolve()));
const loadedData = loadBudgetDataFromStorage(); const loadedData = loadBudgetDataFromStorage();
console.log('예산 데이터 로드됨:', loadedData);
// 새로 로드한 데이터와 현재 데이터가 다를 때만 업데이트 // 새로 로드한 데이터와 현재 데이터가 다를 때만 업데이트
if (JSON.stringify(loadedData) !== JSON.stringify(budgetData)) { if (JSON.stringify(loadedData) !== JSON.stringify(budgetData)) {
console.log('예산 데이터 변경 감지됨, 상태 업데이트'); // 상태 업데이트를 마이크로태스크로 지연
queueMicrotask(() => {
setBudgetData(loadedData); setBudgetData(loadedData);
console.log('예산 데이터 업데이트 완료');
});
} }
// 최근 데이터 로드 시간 기록 // 초기화 상태 업데이트
localStorage.setItem('lastBudgetDataLoadTime', new Date().toISOString());
if (!isInitialized) { if (!isInitialized) {
queueMicrotask(() => {
setIsInitialized(true); setIsInitialized(true);
});
} }
} catch (error) { } catch (error) {
console.error('예산 데이터 로드 중 오류:', error); console.error('예산 데이터 로드 중 오류:', error);
} }
}; };
// 초기 로드 // 초기 로드 - 지연 시간 추가
setTimeout(() => {
loadBudget(); loadBudget();
}, 100); // 지연된 초기 로드
// 이벤트 리스너 설정 // 필수 이벤트만 등록
const handleBudgetUpdate = (e?: StorageEvent) => { const handleBudgetUpdate = () => loadBudget();
console.log('예산 데이터 업데이트 이벤트 감지:', e?.key);
if (!e || e.key === 'budgetData' || e.key === null) {
loadBudget();
}
};
// 이벤트 발생 시 데이터 새로고침 // 필수 이벤트만 등록
window.addEventListener('budgetDataUpdated', () => handleBudgetUpdate()); const budgetUpdateHandler = () => handleBudgetUpdate();
window.addEventListener('storage', handleBudgetUpdate); window.addEventListener('budgetDataUpdated', budgetUpdateHandler);
window.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'visible') {
console.log('페이지 보임: 예산 데이터 새로고침');
loadBudget();
}
});
window.addEventListener('focus', () => {
console.log('창 포커스: 예산 데이터 새로고침');
loadBudget();
});
// 주기적 데이터 검사 (1초마다) - 다른 컴포넌트에서 변경된 사항 감지
const intervalId = setInterval(() => {
const lastSaveTime = localStorage.getItem('lastBudgetSaveTime');
const lastLoadTime = localStorage.getItem('lastBudgetDataLoadTime');
if (lastSaveTime && lastLoadTime && new Date(lastSaveTime) > new Date(lastLoadTime)) {
console.log('새로운 저장 감지됨, 데이터 다시 로드...');
loadBudget();
}
}, 1000);
return () => { return () => {
window.removeEventListener('budgetDataUpdated', () => handleBudgetUpdate()); window.removeEventListener('budgetDataUpdated', budgetUpdateHandler);
window.removeEventListener('storage', handleBudgetUpdate);
window.removeEventListener('visibilitychange', () => {});
window.removeEventListener('focus', () => loadBudget());
clearInterval(intervalId);
}; };
}, [isInitialized, budgetData]); }, [isInitialized, budgetData]);

View File

@@ -16,39 +16,46 @@ export const useTransactionState = () => {
// 초기 트랜잭션 로드 및 이벤트 리스너 설정 // 초기 트랜잭션 로드 및 이벤트 리스너 설정
useEffect(() => { useEffect(() => {
const loadTransactions = () => { // 트랜잭션 로드 함수 - 비동기 처리로 변경
const loadTransactions = async () => {
try {
console.log('트랜잭션 로드 시도 중...'); console.log('트랜잭션 로드 시도 중...');
// 비동기 작업을 마이크로태스크로 지연
await new Promise<void>(resolve => queueMicrotask(() => resolve()));
const storedTransactions = loadTransactionsFromStorage(); const storedTransactions = loadTransactionsFromStorage();
console.log('트랜잭션 로드됨:', storedTransactions.length, '개'); console.log('트랜잭션 로드됨:', storedTransactions.length, '개');
// 상태 업데이트를 마이크로태스크로 지연
queueMicrotask(() => {
setTransactions(storedTransactions); setTransactions(storedTransactions);
});
} catch (error) {
console.error('트랜잭션 로드 오류:', error);
}
}; };
// 초기 로드 // 초기 로드 - 지연 시간 추가
setTimeout(() => {
loadTransactions(); loadTransactions();
}, 100); // 지연된 초기 로드
// 이벤트 리스너 추가 // 이벤트 리스너 추가 - 최소한으로 유지
const handleTransactionUpdate = (e?: StorageEvent) => { const handleTransactionUpdate = (e?: StorageEvent) => {
console.log('트랜잭션 업데이트 이벤트 감지:', e?.key);
if (!e || e.key === 'transactions' || e.key === null) { if (!e || e.key === 'transactions' || e.key === null) {
loadTransactions(); loadTransactions();
} }
}; };
window.addEventListener('transactionUpdated', () => handleTransactionUpdate()); // 필수 이벤트만 등록
window.addEventListener('transactionDeleted', () => handleTransactionUpdate()); const transactionUpdateHandler = () => handleTransactionUpdate();
window.addEventListener('transactionAdded', () => handleTransactionUpdate()); window.addEventListener('transactionUpdated', transactionUpdateHandler);
window.addEventListener('storage', handleTransactionUpdate); window.addEventListener('storage', handleTransactionUpdate);
window.addEventListener('focus', () => {
console.log('창 포커스: 트랜잭션 새로고침');
loadTransactions();
});
return () => { return () => {
window.removeEventListener('transactionUpdated', () => handleTransactionUpdate()); window.removeEventListener('transactionUpdated', transactionUpdateHandler);
window.removeEventListener('transactionDeleted', () => handleTransactionUpdate());
window.removeEventListener('transactionAdded', () => handleTransactionUpdate());
window.removeEventListener('storage', handleTransactionUpdate); window.removeEventListener('storage', handleTransactionUpdate);
window.removeEventListener('focus', () => loadTransactions());
}; };
}, []); }, []);
@@ -74,7 +81,7 @@ export const useTransactionState = () => {
}); });
}, []); }, []);
// 트랜잭션 삭제 함수 - 안정성 개선 // 트랜잭션 삭제 함수 - 성능 최적화 및 안정성 개선
const deleteTransaction = useCallback((transactionId: string) => { const deleteTransaction = useCallback((transactionId: string) => {
// 이미 삭제 중이면 중복 삭제 방지 // 이미 삭제 중이면 중복 삭제 방지
if (isDeleting) { if (isDeleting) {
@@ -82,33 +89,32 @@ export const useTransactionState = () => {
return; return;
} }
console.log('트랜잭션 삭제 시작:', transactionId);
// 중복 삭제 방지 // 중복 삭제 방지
if (lastDeletedId === transactionId) { if (lastDeletedId === transactionId) {
console.log('중복 삭제 요청 무시:', transactionId); console.log('중복 삭제 요청 무시:', transactionId);
return; return;
} }
// 삭제 상태 설정 - 마이크로태스크로 지연
queueMicrotask(() => {
setIsDeleting(true); setIsDeleting(true);
setLastDeletedId(transactionId); setLastDeletedId(transactionId);
// 삭제 작업을 마이크로태스크로 진행하여 UI 차단 방지
queueMicrotask(() => {
try { try {
setTransactions(prev => { setTransactions(prev => {
// 기존 트랜잭션 목록 백업 (문제 발생 시 복원용) // 삭제할 항목 필터링 - 성능 최적화
const originalTransactions = [...prev];
// 삭제할 항목 필터링
const updated = prev.filter(transaction => transaction.id !== transactionId); const updated = prev.filter(transaction => transaction.id !== transactionId);
// 항목이 실제로 삭제되었는지 확인 // 항목이 실제로 삭제되었는지 확인
if (updated.length === originalTransactions.length) { if (updated.length === prev.length) {
console.log('삭제할 트랜잭션을 찾을 수 없음:', transactionId); console.log('삭제할 트랜잭션을 찾을 수 없음:', transactionId);
setIsDeleting(false); return prev; // 변경 없음
return originalTransactions;
} }
// 저장소 업데이트된 목록 저장 // 저장소 업데이트를 마이크로태스크로 진행
queueMicrotask(() => {
saveTransactionsToStorage(updated); saveTransactionsToStorage(updated);
// 토스트 메시지 표시 // 토스트 메시지 표시
@@ -116,6 +122,7 @@ export const useTransactionState = () => {
title: "지출이 삭제되었습니다", title: "지출이 삭제되었습니다",
description: "지출 항목이 성공적으로 삭제되었습니다.", description: "지출 항목이 성공적으로 삭제되었습니다.",
}); });
});
return updated; return updated;
}); });
@@ -127,12 +134,14 @@ export const useTransactionState = () => {
variant: "destructive" variant: "destructive"
}); });
} finally { } finally {
// 삭제 상태 초기화 (1초 후) // 삭제 상태 초기화 (500ms 후) - 시간 단축
setTimeout(() => { setTimeout(() => {
setIsDeleting(false); setIsDeleting(false);
setLastDeletedId(null); setLastDeletedId(null);
}, 1000); }, 500);
} }
});
});
}, [lastDeletedId, isDeleting]); }, [lastDeletedId, isDeleting]);
// 트랜잭션 초기화 함수 // 트랜잭션 초기화 함수

View File

@@ -0,0 +1,36 @@
import { useContext, createContext } from 'react';
import { BudgetData, BudgetPeriod, Transaction } from './types';
// 컨텍스트 인터페이스 정의
export interface BudgetContextType {
transactions: Transaction[];
selectedTab: BudgetPeriod;
setSelectedTab: (tab: BudgetPeriod) => void;
budgetData: BudgetData;
categoryBudgets: Record<string, number>;
getCategorySpending: () => Array<{
title: string;
current: number;
total: number;
}>;
addTransaction: (transaction: Transaction) => void;
updateTransaction: (transaction: Transaction) => void;
deleteTransaction: (id: string) => void;
handleBudgetGoalUpdate: (type: BudgetPeriod, amount: number, newCategoryBudgets?: Record<string, number>) => void;
resetBudgetData?: () => void; // 선택적 필드로 추가
}
// 컨텍스트 생성
export const BudgetContext = createContext<BudgetContextType | undefined>(undefined);
/**
* 예산 컨텍스트에 접근하기 위한 커스텀 훅
* BudgetProvider 내부에서만 사용해야 함
*/
export const useBudget = (): BudgetContextType => {
const context = useContext(BudgetContext);
if (context === undefined) {
throw new Error('useBudget는 BudgetProvider 내부에서 사용해야 합니다');
}
return context;
};

View File

@@ -2,7 +2,7 @@ import { useState, useEffect, useCallback } from 'react';
import { resetAllData } from '@/contexts/budget/storage'; import { resetAllData } from '@/contexts/budget/storage';
import { resetAllStorageData } from '@/utils/storageUtils'; import { resetAllStorageData } from '@/utils/storageUtils';
import { clearCloudData } from '@/utils/syncUtils'; import { clearCloudData } from '@/utils/syncUtils';
import { useAuth } from '@/contexts/auth/AuthProvider'; import { useAuth } from '@/contexts/auth';
export const useDataInitialization = (resetBudgetData?: () => void) => { export const useDataInitialization = (resetBudgetData?: () => void) => {
const [isInitialized, setIsInitialized] = useState(false); const [isInitialized, setIsInitialized] = useState(false);

View File

@@ -4,7 +4,7 @@ import { useNavigate } from 'react-router-dom';
import { useToast } from '@/hooks/useToast.wrapper'; import { useToast } from '@/hooks/useToast.wrapper';
import { resetAllStorageData } from '@/utils/storageUtils'; import { resetAllStorageData } from '@/utils/storageUtils';
import { clearCloudData } from '@/utils/sync/clearCloudData'; import { clearCloudData } from '@/utils/sync/clearCloudData';
import { useAuth } from '@/contexts/auth/AuthProvider'; import { useAuth } from '@/contexts/auth';
import { isSyncEnabled, setSyncEnabled } from '@/utils/sync/syncSettings'; import { isSyncEnabled, setSyncEnabled } from '@/utils/sync/syncSettings';
export interface DataResetResult { export interface DataResetResult {