Skip to content

Conversation

@Han-wo
Copy link
Collaborator

@Han-wo Han-wo commented Dec 16, 2024

#️⃣ 이슈

📝 작업 내용

메인페이지의 각 섹션을 구분하여 분리하고 메모이제이션을 통해서 케러셀 동작시 리랜더링 되던 부분을 변경했습니다.

이전에는 캐러셀 동작시 우측 사이드바 및 테이블도 같이 리랜더링이 되었는데 변경후엔 케러셀만 리랜더링됩니다

(캐러셀은 움직이면서 안에 컨텐츠가 새로 보이니까 어쩔수 없이 리랜더링됩니다 ㅜㅠ)

📸 스크린샷

이전

default.webm

변경후

default.webm

✅ 체크 리스트

  • 적절한 Title 작성
  • 적절한 Label 지정
  • Assignee 및 Reviewer 지정
  • 로컬 작동 확인
  • Merge 되는 브랜치 확인

👩‍💻 공유 포인트 및 논의 사항

Summary by CodeRabbit

  • 새로운 기능
    • MainContentSidebar 컴포넌트 추가.
    • 주식 및 뉴스 데이터 관련 새로운 컴포넌트 RankingSection, TableWrapper, Sidebar 추가.
  • 버그 수정
    • 에러 경계를 통해 사용자 친화적인 에러 메시지 제공.
  • 문서화
    • 새로운 인터페이스 StockDataNews 추가.
    • 기존 인터페이스 NewsFluctuation으로 변경됨.

@Han-wo Han-wo added 우선순위: MEDIUM New feature or request ♻️REFACTOR Refactor code labels Dec 16, 2024
@Han-wo Han-wo self-assigned this Dec 16, 2024
@Han-wo Han-wo linked an issue Dec 16, 2024 that may be closed by this pull request
2 tasks
@coderabbitai
Copy link

coderabbitai bot commented Dec 16, 2024

Walkthrough

이 풀 리퀘스트는 메인 페이지의 구조를 리팩토링하고 최적화하는 작업을 포함합니다. 주요 변경 사항은 여러 개의 개별 컴포넌트를 MainContentSidebar 컴포넌트로 통합하고, 타입 정의를 재구조화하며, 렌더링 성능을 개선하기 위해 React의 memo 함수를 활용하는 것입니다.

Changes

파일 변경 요약
src/api/kospi-kosdac/index.ts StockIndexResponse, StockData 인터페이스 제거 및 외부 모듈에서 타입 가져오기
src/app/main/_components/main-contents.tsx 새로운 MainContent 컴포넌트 추가, ErrorBoundary 사용
src/app/main/_components/my-info.tsx 새로운 Sidebar 컴포넌트 추가
src/app/main/_components/ranking-section.tsx 새로운 RankingSection 컴포넌트 추가
src/app/main/_components/table-wrapper.tsx 새로운 TableWrapper 컴포넌트 추가
src/app/main/types/index.ts 타입 인터페이스 재정의 및 추가
src/app/page.tsx 컴포넌트 구조 대폭 변경, 새로운 MainContentSidebar 컴포넌트로 대체

Assessment against linked issues

목표 해결 여부 설명
메인페이지 리랜더링 최적화 [#80]

Possibly related PRs

Suggested labels

✨ FEAT, 우선순위: HIGH

Suggested reviewers

  • cindycho0423

Poem

🐰 코드의 숲을 달리는 토끼
컴포넌트들을 한데 모아
최적화의 길을 열어가네
메모리제이션으로 빛나는 길
성능의 토끼, 재빠르게 뛰어~! 🏃‍♀️✨

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request.


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?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

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)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@github-actions
Copy link

Copy link

@coderabbitai coderabbitai bot left a 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문을 다음과 같이 그룹화하면 코드의 가독성이 향상될 것 같습니다:

  1. React 관련 import
  2. 컴포넌트 import
  3. 타입 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

📥 Commits

Reviewing files that changed from the base of the PR and between 4dfddd6 and 2441f32.

📒 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: 컴포넌트 구조 개선이 잘 되었습니다

MainContentSidebar 컴포넌트로 분리하여 관심사를 명확하게 분리한 것이 좋습니다. 이는 PR의 목적인 리렌더링 최적화에도 도움이 됩니다.

Comment on lines +18 to +41
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>
);
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codebase verification

🛠️ Refactor suggestion

성능 최적화 및 에러 처리 검토 결과

검토 결과 다음과 같은 사항들이 확인되었습니다:

  1. RankingSection 컴포넌트만 memo로 최적화되어 있어, SearchStock, StockIndexCarousel, NewsCarousel 컴포넌트들의 메모이제이션이 필요합니다.
  2. ErrorBoundary는 이미 적절한 fallback UI를 구현하고 있어 추가 개선이 필요하지 않습니다. 현재 구현에는 에러 메시지, 설명, 새로고침 버튼이 포함되어 있습니다.

개선이 필요한 부분:

  • SearchStock 컴포넌트에 memo 적용
  • StockIndexCarousel 컴포넌트에 memo 적용
  • NewsCarousel 컴포넌트에 memo 적용
🔗 Analysis chain

컴포넌트 최적화 및 에러 처리 개선 제안

컴포넌트 구현이 전반적으로 잘 되어있지만, 몇 가지 개선사항을 제안드립니다:

  1. 자식 컴포넌트들도 memo로 최적화되어 있는지 확인이 필요합니다.
  2. 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

@Han-wo Han-wo requested a review from cindycho0423 December 16, 2024 07:44
@Han-wo Han-wo merged commit e3d046c into develop Dec 17, 2024
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

우선순위: MEDIUM New feature or request ♻️REFACTOR Refactor code

Projects

None yet

Development

Successfully merging this pull request may close these issues.

refactor: 메인페이지 리랜더링 최적화

2 participants