-
Notifications
You must be signed in to change notification settings - Fork 1
refactor: 메인페이지 리랜더링 최적화 #82
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
Walkthrough이 풀 리퀘스트는 메인 페이지의 구조를 리팩토링하고 최적화하는 작업을 포함합니다. 주요 변경 사항은 여러 개의 개별 컴포넌트를 Changes
Assessment against linked issues
Possibly related PRs
Suggested labels
Suggested reviewers
Poem
Tip CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
🔭 Outside diff range comments (1)
src/app/page.tsx (1)
Line range hint
10-16: QueryClient 설정을 외부 파일로 분리하세요QueryClient 설정을 별도의 설정 파일로 분리하면 재사용성과 유지보수성이 향상됩니다.
+ // src/config/query-client.ts + export const queryClientConfig = { + defaultOptions: { + queries: { + staleTime: 0, + retry: 1, + }, + }, + }; - const queryClient = new QueryClient({ - defaultOptions: { - queries: { - staleTime: 0, - retry: 1, - }, - }, - }); + const queryClient = new QueryClient(queryClientConfig);
🧹 Nitpick comments (10)
src/app/main/_components/table-wrapper.tsx (1)
1-9: 컴포넌트 구현이 깔끔하고 적절합니다!메모이제이션을 통한 최적화가 잘 되어있습니다. 다만, className을 좀 더 명시적으로 작성하면 좋을 것 같습니다.
- return <div className="w-full">{children}</div>; + return <div className="table-wrapper w-full">{children}</div>;src/app/main/types/index.ts (1)
26-32: Fluctuation 인터페이스에 JSDoc 문서화 추가 제안각 필드의 의미와 단위를 명확히 하기 위해 문서화를 추가하면 좋을 것 같습니다.
+/** + * 주식 가격 변동 정보를 나타내는 인터페이스 + * @property rank - 순위 + * @property stockName - 종목명 + * @property currentPrice - 현재가 (원) + * @property prevChangePrice - 전일 대비 변동 금액 (원) + * @property prevSign - 등락 기호 + * @property prevChangeRate - 전일 대비 등락률 (%) + */ export interface Fluctuation { rank: number; stockName: string; currentPrice: number; prevChangePrice: number; prevSign: string; prevChangeRate: number; }src/app/main/_components/my-info.tsx (1)
9-10: Tailwind 커스텀 값 설정 필요
w-330와 같은 커스텀 값은 Tailwind 설정에 추가하는 것이 좋습니다. 현재는 하드코딩된 값으로 보입니다.// tailwind.config.js module.exports = { theme: { extend: { width: { + '330': '330px', }, }, }, }src/api/kospi-kosdac/index.ts (1)
Line range hint
14-18: 에러 처리를 더 구체적으로 개선하세요현재 구현된 에러 처리는 모든 실패 케이스에 대해 동일한 에러 메시지를 반환합니다. 각각의 API 응답에 대해 더 구체적인 에러 처리가 필요합니다.
- if (!kospiRes.ok || !kosdaqRes.ok) { - throw new Error("Failed to fetch stock data"); + if (!kospiRes.ok) { + throw new Error("KOSPI 데이터 조회 실패"); + } + if (!kosdaqRes.ok) { + throw new Error("KOSDAQ 데이터 조회 실패"); }src/app/main/_components/ranking-section.tsx (2)
22-24: 에러 메시지를 더 상세하게 개선하세요현재 에러 메시지가 너무 단순합니다. 사용자에게 문제 해결을 위한 가이드나 재시도 방법을 제공하는 것이 좋습니다.
- <ErrorBoundary errorMessage="거래량 순위를 불러올 수 없습니다"> + <ErrorBoundary + errorMessage="거래량 순위를 불러올 수 없습니다. 잠시 후 새로고침해 주세요." + retryButton={true} + >Also applies to: 27-29
18-20: CSS 클래스명을 더 유지보수하기 쉽게 개선하세요현재 하드코딩된 마진과 패딩 값들을 CSS 변수나 Tailwind 설정으로 관리하면 일관성 있는 유지보수가 가능합니다.
- <div className="mb-30 flex flex-col gap-20"> - <h2 className="mt-80 text-24-700">실시간 랭킹</h2> + <div className="mb-section flex flex-col gap-default"> + <h2 className="mt-header text-title-bold">실시간 랭킹</h2>src/app/page.tsx (1)
Line range hint
18-31: 데이터 프리페칭 전략을 검토하세요현재 모든 데이터를 동시에 프리페치하고 있습니다. 사용자 경험을 위해 중요도에 따라 프리페치 우선순위를 조정하는 것을 고려해보세요.
+ // 중요 데이터 먼저 프리페치 const initialStockData = await getInitialStockData(); await queryClient.prefetchQuery({ queryKey: ["stockIndex"], queryFn: getInitialStockData, initialData: initialStockData, + priority: 'high' }); + // 나머지 데이터는 병렬로 프리페치 + await Promise.all([ + queryClient.prefetchQuery({ + queryKey: ["news"], + queryFn: getNews, + initialData: await getNews(), + }), + queryClient.prefetchQuery({ + queryKey: ["trading"], + queryFn: getTradingVolume, + initialData: await getTradingVolume(), + }), + queryClient.prefetchQuery({ + queryKey: ["fluctuation"], + queryFn: getFluctuation, + initialData: await getFluctuation(), + }), + ]);src/app/main/_components/main-contents.tsx (3)
1-9: import문 구성 개선 제안import문을 다음과 같이 그룹화하면 코드의 가독성이 향상될 것 같습니다:
- React 관련 import
- 컴포넌트 import
- 타입 import
다음과 같이 수정해보세요:
import { memo } from "react"; +// Components import NewsCarousel from "@/app/main/_components/news-carousel"; import SearchStock from "@/app/main/_components/search-stock"; import StockIndexCarousel from "@/app/main/_components/stock-carousel"; import ErrorBoundary from "@/components/common/error-boundary"; import RankingSection from "./ranking-section"; +// Types import { Fluctuation, News, StockData, TradingVolume } from "../types";
11-16: 인터페이스 문서화 추가 제안타입스크립트 인터페이스에 JSDoc 문서를 추가하면 다른 개발자들이 컴포넌트를 더 쉽게 이해하고 사용할 수 있을 것 같습니다.
다음과 같이 수정해보세요:
+/** + * MainContent 컴포넌트의 props 인터페이스 + * @property {StockData} initialStockData - 초기 주식 데이터 + * @property {News[]} initialNews - 초기 뉴스 데이터 배열 + * @property {TradingVolume[]} traddata - 거래량 데이터 배열 + * @property {Fluctuation[]} flucdata - 등락률 데이터 배열 + */ interface MainContentProps { initialStockData: StockData; initialNews: News[]; traddata: TradingVolume[]; flucdata: Fluctuation[]; }
43-43: 메모이제이션 최적화 제안현재 memo의 기본 비교 함수를 사용하고 있는데, 배열 props가 있으므로 커스텀 비교 함수를 추가하면 성능을 더욱 최적화할 수 있습니다.
다음과 같이 수정해보세요:
-export default memo(MainContent); +export default memo(MainContent, (prevProps, nextProps) => { + return ( + prevProps.initialStockData === nextProps.initialStockData && + prevProps.initialNews === nextProps.initialNews && + prevProps.traddata === nextProps.traddata && + prevProps.flucdata === nextProps.flucdata + ); +});
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (7)
src/api/kospi-kosdac/index.ts(1 hunks)src/app/main/_components/main-contents.tsx(1 hunks)src/app/main/_components/my-info.tsx(1 hunks)src/app/main/_components/ranking-section.tsx(1 hunks)src/app/main/_components/table-wrapper.tsx(1 hunks)src/app/main/types/index.ts(2 hunks)src/app/page.tsx(2 hunks)
🔇 Additional comments (6)
src/app/main/types/index.ts (1)
7-10: StockData 인터페이스의 null 처리 검토 필요
kospi와 kosdaq이 null일 수 있는 상황에 대한 처리가 필요할 것 같습니다. 컴포넌트에서 이에 대한 적절한 예외 처리나 로딩 상태 표시가 구현되어 있는지 확인해주세요.
✅ Verification successful
null 처리가 적절히 구현되어 있음을 확인했습니다
코드베이스 분석 결과, StockData의 null 처리가 다음과 같이 적절히 구현되어 있습니다:
- API 호출 실패 시
getInitialStockData에서 명시적으로{ kospi: null, kosdaq: null }을 반환합니다. StockIndexCarousel컴포넌트에서 데이터를 적절히 처리하며,MarketIndexCard를 통해 각 지수 데이터를 표시합니다.- React Query를 사용하여 데이터 상태 관리와 재시도 로직이 구현되어 있습니다.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Check for null handling in components using StockData
ast-grep --pattern 'const $_ = ({ kospi, kosdaq }: StockData) => {
$$$
}'
Length of output: 77
Script:
#!/bin/bash
# Search for files that import StockData
rg "import.*StockData" -l
# Search for usage of StockData type
rg "StockData" -A 3
# Search for components handling kospi or kosdaq
rg "kospi|kosdaq" -A 3
Length of output: 8352
src/app/main/_components/my-info.tsx (2)
11-17: 에러 처리가 잘 구현되어 있습니다!
ErrorBoundary를 사용한 컴포넌트별 에러 처리가 잘 되어 있습니다. 사용자 경험을 위해 에러 메시지도 한글로 잘 작성되어 있습니다.
22-22: 메모이제이션 구현이 적절합니다
리렌더링 최적화를 위한 memo 사용이 적절합니다. PR의 목적에 잘 부합합니다.
src/api/kospi-kosdac/index.ts (1)
Line range hint 6-9: 캐시 전략 검토가 필요합니다
no-store 캐시 전략은 모든 요청마다 새로운 데이터를 가져오게 됩니다. 실시간 데이터가 필요한지, 아니면 일정 시간 동안 캐시를 활용할 수 있는지 검토가 필요합니다.
✅ Verification successful
Let me generate additional scripts to check if these endpoints are related to real-time data by examining the API routes and any related documentation.
no-store 캐시 전략이 적절합니다
검색 결과를 보면 해당 엔드포인트들이 실시간 데이터를 제공하는 기능들과 연관되어 있습니다:
- KOSPI/KOSDAQ 지수는 실시간으로 변동하는 데이터입니다
- 코드베이스 전반에 걸쳐 "실시간 호가", "실시간 랭킹", "실시간 인기 종목" 등의 기능이 구현되어 있습니다
- 주식 차트, 거래량 등의 데이터도 최신 정보가 중요한 정보입니다
따라서 no-store 캐시 전략을 사용하여 항상 최신 데이터를 가져오는 현재의 구현이 적절합니다.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Check cache strategy usage across the codebase
# Search for cache configuration patterns
rg -A 2 'cache:.*"no-store"'
Length of output: 1512
Script:
#!/bin/bash
# Check for API documentation or comments about data freshness requirements
rg -i "실시간|갱신|업데이트" --type ts
# Check for any comments or documentation near the cache configuration
rg -B 3 -A 1 'cache:.*"no-store"' --type ts
# Look for README or documentation files
fd -e md
Length of output: 3436
src/app/main/_components/ranking-section.tsx (1)
36-36: 메모이제이션 전략이 적절합니다
memo를 사용하여 불필요한 리렌더링을 방지한 것이 좋습니다. 특히 실시간 데이터를 다루는 컴포넌트에서 이는 중요한 최적화입니다.
src/app/page.tsx (1)
40-46: 컴포넌트 구조 개선이 잘 되었습니다
MainContent와 Sidebar 컴포넌트로 분리하여 관심사를 명확하게 분리한 것이 좋습니다. 이는 PR의 목적인 리렌더링 최적화에도 도움이 됩니다.
| function MainContent({ | ||
| initialStockData, | ||
| initialNews, | ||
| traddata, | ||
| flucdata, | ||
| }: MainContentProps) { | ||
| return ( | ||
| <div className="flex flex-1 flex-col p-10 pt-30 md:px-32 lg:max-w-[calc(100%-320px)]"> | ||
| <ErrorBoundary errorMessage="검색 기능을 일시적으로 사용할 수 없습니다"> | ||
| <SearchStock /> | ||
| </ErrorBoundary> | ||
|
|
||
| <ErrorBoundary errorMessage="주가 정보를 불러올 수 없습니다"> | ||
| <StockIndexCarousel initialData={initialStockData} /> | ||
| </ErrorBoundary> | ||
|
|
||
| <RankingSection traddata={traddata} flucdata={flucdata} /> | ||
|
|
||
| <ErrorBoundary errorMessage="뉴스를 불러올 수 없습니다"> | ||
| <NewsCarousel initialData={initialNews} /> | ||
| </ErrorBoundary> | ||
| </div> | ||
| ); | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💡 Codebase verification
🛠️ Refactor suggestion
성능 최적화 및 에러 처리 검토 결과
검토 결과 다음과 같은 사항들이 확인되었습니다:
- RankingSection 컴포넌트만 memo로 최적화되어 있어, SearchStock, StockIndexCarousel, NewsCarousel 컴포넌트들의 메모이제이션이 필요합니다.
- ErrorBoundary는 이미 적절한 fallback UI를 구현하고 있어 추가 개선이 필요하지 않습니다. 현재 구현에는 에러 메시지, 설명, 새로고침 버튼이 포함되어 있습니다.
개선이 필요한 부분:
SearchStock컴포넌트에 memo 적용StockIndexCarousel컴포넌트에 memo 적용NewsCarousel컴포넌트에 memo 적용
🔗 Analysis chain
컴포넌트 최적화 및 에러 처리 개선 제안
컴포넌트 구현이 전반적으로 잘 되어있지만, 몇 가지 개선사항을 제안드립니다:
- 자식 컴포넌트들도 memo로 최적화되어 있는지 확인이 필요합니다.
- ErrorBoundary에 fallback UI를 추가하면 좋을 것 같습니다.
자식 컴포넌트들의 메모이제이션 상태를 확인해보겠습니다:
ErrorBoundary 개선 예시:
<ErrorBoundary errorMessage="검색 기능을 일시적으로 사용할 수 없습니다">
<SearchStock />
</ErrorBoundary>↓
<ErrorBoundary
errorMessage="검색 기능을 일시적으로 사용할 수 없습니다"
+ fallback={
+ <div className="flex items-center justify-center p-4 bg-gray-100 rounded-lg">
+ <p className="text-gray-600">검색 기능을 일시적으로 사용할 수 없습니다</p>
+ <button
+ onClick={() => window.location.reload()}
+ className="ml-2 px-4 py-2 bg-blue-500 text-white rounded"
+ >
+ 다시 시도
+ </button>
+ </div>
+ }
>
<SearchStock />
</ErrorBoundary>Let me check the ErrorBoundary implementation to complete the verification:
Let me try a different approach to find the ErrorBoundary implementation:
Let me check the complete ErrorBoundary implementation:
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: 자식 컴포넌트들의 메모이제이션 확인
echo "Checking child components for memo usage..."
# SearchStock 컴포넌트 확인
ast-grep --pattern 'export default memo($_)' src/app/main/_components/search-stock.tsx
# StockIndexCarousel 컴포넌트 확인
ast-grep --pattern 'export default memo($_)' src/app/main/_components/stock-carousel.tsx
# NewsCarousel 컴포넌트 확인
ast-grep --pattern 'export default memo($_)' src/app/main/_components/news-carousel.tsx
# RankingSection 컴포넌트 확인
ast-grep --pattern 'export default memo($_)' src/app/main/_components/ranking-section.tsx
Length of output: 543
Script:
#!/bin/bash
# Check ErrorBoundary implementation
ast-grep --pattern 'class ErrorBoundary extends React.Component {
$$$
}'
# Also check if there's a functional component implementation
ast-grep --pattern 'function ErrorBoundary($_) {
$$$
}'
# Check if there's any file containing ErrorBoundary in its name
fd ErrorBoundary
Length of output: 155
Script:
#!/bin/bash
# Search for ErrorBoundary in all files
rg -l "ErrorBoundary"
# Search for ErrorBoundary implementation with context
rg "class.*ErrorBoundary|function.*ErrorBoundary" -A 10
Length of output: 1110
Script:
#!/bin/bash
# Get full ErrorBoundary implementation
cat src/components/common/error-boundary/index.tsx
# Check if there's any existing fallback UI implementation
rg "fallback.*=" src/components/common/error-boundary/index.tsx -A 3
Length of output: 1948
#️⃣ 이슈
📝 작업 내용
메인페이지의 각 섹션을 구분하여 분리하고 메모이제이션을 통해서 케러셀 동작시 리랜더링 되던 부분을 변경했습니다.
이전에는 캐러셀 동작시 우측 사이드바 및 테이블도 같이 리랜더링이 되었는데 변경후엔 케러셀만 리랜더링됩니다
(캐러셀은 움직이면서 안에 컨텐츠가 새로 보이니까 어쩔수 없이 리랜더링됩니다 ㅜㅠ)
📸 스크린샷
이전
default.webm
변경후
default.webm
✅ 체크 리스트
👩💻 공유 포인트 및 논의 사항
Summary by CodeRabbit
MainContent및Sidebar컴포넌트 추가.RankingSection,TableWrapper,Sidebar추가.StockData및News추가.News가Fluctuation으로 변경됨.