Communitygithub.com

ComeOnOliver/skillshub

Next.js 16+는 기본적으로 App Router와 Server Components를 사용합니다. Client Components는 상호작용이 필요한 경우(훅, 이벤트 핸들러, 브라우저 API)에만 사용됩니다.

skillshub란 무엇인가요?

이 스킬은 Next.js 16+ 애플리케이션에서 Server Components와 Client Components를 효과적으로 구분하여 사용하는 방법을 제공합니다. App Router 환경에서 기본적으로 Server Components를 사용하고, 상호작용이 필요한 부분에만 Client Components를 적용하는 패턴을 명확히 제시합니다. ProtectedRoute, LoadingSpinner, 폼 핸들링, ToastNotification, 드래그 앤 드롭, 실행 취소/재실행 등 자주 사용되는 컴포넌트 패턴의 구체적인 코드 예제를 포함하고 있습니다. 또한 Tailwind CSS 유틸리티 클래스 사용법, WCAG 2.1 AA 접근성 패턴, 파일 명명 규칙, 그리고 프레임워크 헌법 요구사항(FR-033~FR-039) 준수 방법을 상세히 다루고 있어, 팀 전체가 일관된 코드 스타일과 아키텍처를 유지하는 데 도움을 줍니다.

지원 대상~Claude Code~Codex CLI✓Cursor
npx skills add https://github.com/ComeOnOliver/skillshub/tree/HEAD/skills/aiskillstore/marketplace/asmayaseen/frontend-component

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

프론트엔드 컴포넌트 스킬

목적: 서버/클라이언트 패턴과 기존 컴포넌트 구조를 따라 Next.js 컴포넌트를 생성하기 위한 가이드입니다.

개요

Next.js 16+는 기본적으로 App Router와 Server Components를 사용합니다. Client Components는 상호작용이 필요한 경우(훅, 이벤트 핸들러, 브라우저 API)에만 사용됩니다.

서버 vs 클라이언트 컴포넌트

서버 컴포넌트(기본값)

사용 시기:

  • 페이지 및 레이아웃
  • 정적 콘텐츠
  • API로부터의 데이터 페칭(가능한 경우)
  • SEO 최적화 콘텐츠

패턴:

// "use client" 지시어 없음
import { Metadata } from "next";

export const metadata: Metadata = {
  title: "페이지 제목",
};

export default function PageComponent() {
  return <div>정적 콘텐츠</div>;
}

예시: frontend/app/layout.tsx, frontend/app/page.tsx

클라이언트 컴포넌트(필요 시)

사용 시기:

  • 인터랙티브 요소(버튼, 폼, 입력 필드)
  • 이벤트 핸들러(onClick, onChange 등)
  • React 훅(useState, useEffect, useRouter 등)
  • 브라우저 API(localStorage, window, document 등)
  • 실시간 업데이트
  • 드래그 앤 드롭 기능

패턴:

"use client"; // 반드시 첫 줄에 위치

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";

interface ComponentProps {
  prop1: string;
  prop2?: number;
}

export default function ComponentName({ prop1, prop2 }: ComponentProps) {
  const router = useRouter();
  const [state, setState] = useState("");

  useEffect(() => {
    // 부수 효과
  }, []);

  return <div>{/* 컴포넌트 JSX */}</div>;
}

예시: frontend/components/ProtectedRoute.tsx, frontend/app/signup/page.tsx

컴포넌트 구조 템플릿

"use client"; // 클라이언트 컴포넌트인 경우에만

/**
 * 컴포넌트 이름
 *
 * 이 컴포넌트가 수행하는 작업에 대한 간략한 설명
 */

import { useState, useEffect } from "react";
import { ComponentType } from "@/types";
import { cn } from "@/lib/utils";

interface ComponentProps {
  prop1: string;
  prop2?: number;
  className?: string;
}

export default function ComponentName({ prop1, prop2, className }: ComponentProps) {
  // 상태
  const [state, setState] = useState("");

  // 효과
  useEffect(() => {
    // 부수 효과
  }, []);

  // 핸들러
  const handleClick = () => {
    // 핸들러 로직
  };

  // 렌더링
  return (
    <div className={cn("base-classes", className)}>
      {/* 컴포넌트 콘텐츠 */}
    </div>
  );
}

특정 컴포넌트 패턴

1. ProtectedRoute 패턴

출처: frontend/components/ProtectedRoute.tsx

"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { isAuthenticated } from "@/lib/auth";
import LoadingSpinner from "./LoadingSpinner";

interface ProtectedRouteProps {
  children: React.ReactNode;
}

export default function ProtectedRoute({ children }: ProtectedRouteProps) {
  const router = useRouter();
  const [isAuthorized, setIsAuthorized] = useState(false);
  const [isChecking, setIsChecking] = useState(true);

  useEffect(() => {
    async function checkAuth() {
      try {
        const authenticated = await isAuthenticated();

        if (!authenticated) {
          const currentPath = window.location.pathname;
          if (currentPath !== "/signin") {
            sessionStorage.setItem("redirectAfterLogin", currentPath);
          }
          router.push("/signin");
        } else {
          setIsAuthorized(true);
        }
      } catch (error) {
        console.error("인증 확인 실패:", error);
        router.push("/signin");
      } finally {
        setIsChecking(false);
      }
    }

    checkAuth();
  }, [router]);

  if (isChecking) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <LoadingSpinner size="large" />
      </div>
    );
  }

  if (!isAuthorized) {
    return null;
  }

  return <>{children}</>;
}

패턴:

  • 마운트 시 인증 확인
  • 확인 중 로딩 스피너 표시
  • 의도한 대상 경로를 sessionStorage에 저장
  • 인증되지 않은 경우 /signin으로 리디렉션
  • 인증된 경우에만 children 렌더링

2. LoadingSpinner 패턴

출처: frontend/components/LoadingSpinner.tsx

interface LoadingSpinnerProps {
  size?: "small" | "medium" | "large";
  color?: string;
  label?: string;
}

export default function LoadingSpinner({
  size = "medium",
  color = "blue",
  label = "로딩 중...",
}: LoadingSpinnerProps) {
  const sizeClasses = {
    small: "w-4 h-4 border-2",
    medium: "w-8 h-8 border-3",
    large: "w-12 h-12 border-4",
  };

  const colorClasses = {
    blue: "border-blue-600 border-t-transparent",
    gray: "border-gray-600 border-t-transparent",
    white: "border-white border-t-transparent",
  };

  const spinnerClass = `${sizeClasses[size]} ${
    colorClasses[color as keyof typeof colorClasses] || colorClasses.blue
  } rounded-full animate-spin`;

  return (
    <div
      className="flex items-center justify-center"
      role="status"
      aria-label={label}
      aria-live="polite"
    >
      <div className={spinnerClass}></div>
      <span className="sr-only">{label}</span>
    </div>
  );
}

패턴:

  • 여러 크기(small, medium, large)
  • 여러 색상(blue, gray, white)
  • 접근성 레이블(role="status", aria-label, aria-live)
  • sr-only 클래스를 사용한 스크린 리더 텍스트

3. 폼 핸들링 패턴

출처: frontend/app/signup/page.tsx

"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { api } from "@/lib/api";
import { isValidEmail, getPasswordStrength } from "@/lib/utils";

export default function SignupPage() {
  const router = useRouter();
  const [formData, setFormData] = useState({
    name: "",
    email: "",
    password: "",
  });
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [isLoading, setIsLoading] = useState(false);
  const [apiError, setApiError] = useState("");

  const validateForm = (): boolean => {
    const newErrors: Record<string, string> = {};

    if (!formData.name.trim()) {
      newErrors.name = "이름은 필수 항목입니다";
    }

    if (!formData.email.trim()) {
      newErrors.email = "이메일은 필수 항목입니다";
    } else if (!isValidEmail(formData.email)) {
      newErrors.email = "유효한 이메일 주소를 입력하세요";
    }

    // 추가 유효성 검사...

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setApiError("");

    if (!validateForm()) {
      return;
    }

    setIsLoading(true);

    try {
      const response = await api.signup(formData);
      if (response.success) {
        router.push("/dashboard");
      } else {
        setApiError(response.message || "회원가입 실패");
      }
    } catch (error: any) {
      setApiError(error.message || "오류가 발생했습니다");
    } finally {
      setIsLoading(false);
    }
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData((prev) => ({ ...prev, [name]: value }));
    // 사용자가 입력을 시작하면 해당 필드의 오류를 지움
    if (errors[name]) {
      setErrors((prev) => ({ ...prev, [name]: "" }));
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      {/* 폼 필드 */}
    </form>
  );
}

패턴:

  • 폼 데이터, 오류, 로딩, API 오류에 대한 별도의 상태
  • 불리언을 반환하는 유효성 검사 함수
  • 입력 변경 시 오류 지우기
  • 제출 중 로딩 상태
  • 오류 처리를 위한 try-catch
  • 성공 시 리디렉션

4. ToastNotification 패턴

출처: frontend/components/ToastNotification.tsx

"use client";

import { useEffect, useState } from "react";
import { ToastMessage, ToastType } from "@/types";

export function useToast() {
  const [toasts, setToasts] = useState<ToastMessage[]>([]);

  const showToast = (type: ToastType, message: string, duration?: number) => {
    const id = `toast-${Date.now()}-${Math.random()}`;
    const newToast: ToastMessage = {
      id,
      type,
      message,
      duration,
    };
    setToasts((prev) => [...prev, newToast]);
  };

  const dismissToast = (id: string) => {
    setToasts((prev) => prev.filter((toast) => toast.id !== id));
  };

  return {
    toasts,
    showToast,
    dismissToast,
    success: (message: string, duration?: number) => showToast("success", message, duration),
    error: (message: string, duration?: number) => showToast("error", message, duration),
    // ...
  };
}

패턴:

  • 토스트 관리를 위한 커스텀 훅
  • 지속 시간에 따른 자동 닫기
  • 여러 토스트 쌓기
  • 헬퍼 메서드(success, error, warning, info)

Tailwind CSS 패턴

1. 유틸리티 클래스만 사용

<div className="flex items-center justify-center gap-4 p-6 bg-white rounded-lg shadow-md">

패턴: 인라인 스타일 없이 Tailwind 유틸리티 클래스 사용

2. cn() 유틸리티를 사용한 조건부 클래스

import { cn } from "@/lib/utils";

<div className={cn(
  "base-classes",
  condition && "conditional-classes",
  className // prop 오버라이드 허용
)}>

패턴: 조건부 클래스에 @/lib/utils의 cn() 사용

3. 다크 모드 지원

<div className="bg-white dark:bg-gray-800 text-gray-900 dark:text-white">

패턴: 다크 모드 스타일에 dark: 접두사 사용

4. 반응형 디자인

<div className="w-full sm:w-1/2 md:w-1/3 lg:w-1/4">

패턴: 중단점 접두사 사용(sm:, md:, lg:, xl:)

접근성 패턴(WCAG 2.1 AA)

1. ARIA 레이블

<button aria-label="대화상자 닫기">×</button>
<div role="status" aria-live="polite" aria-label="로딩 중...">

패턴: 아이콘만 있는 버튼에는 항상 aria-label 제공

2. 시맨틱 HTML

<nav>
  <ul>
    <li><a href="/">홈</a></li>
  </ul>
</nav>

패턴: 시맨틱 HTML 요소 사용(nav, main, section, article 등)

3. 키보드 탐색

<button
  onClick={handleClick}
  onKeyDown={(e) => {
    if (e.key === "Enter" || e.key === " ") {
      handleClick();
    }
  }}
>

패턴: 모든 상호작용 요소에 키보드 접근성 보장

4. 스크린 리더 텍스트

<span className="sr-only">콘텐츠 로딩 중</span>

패턴: 스크린 리더 전용 텍스트에 sr-only 클래스 사용

5. 포커스 관리

<input
  autoFocus
  className="focus:outline-none focus:ring-2 focus:ring-blue-500"
/>

패턴: 항상 가시적인 포커스 표시기 제공

파일 명명 규칙

  • 페이지: kebab-case (예: signup.tsx, signin.tsx)
  • 컴포넌트: PascalCase (예: TaskList.tsx, TaskItem.tsx)
  • 레이아웃: layout.tsx
  • 오류 페이지: error.tsx, not-found.tsx

헌법 요구사항

  • FR-033: Next.js 16+ App Router 구조 ✅
  • FR-034: 기본 서버 컴포넌트, 필요 시 클라이언트 ✅
  • FR-035: 오류 경계 ✅
  • FR-036: WCAG 2.1 AA 준수 ✅
  • FR-037: TypeScript 엄격 모드 ✅
  • FR-038: Prettier 포맷팅 ✅
  • FR-039: ESLint 규칙 ✅

참조

  • 명세서: specs/002-frontend-todo-app/spec.md - 컴포넌트 명세
  • 기존 컴포넌트: frontend/components/*.tsx - 컴포넌트 예시
  • 기존 페이지: frontend/app/*.tsx - 페이지 예시

고급 컴포넌트 패턴

1. 드래그 앤 드롭 패턴(Phase 7 - T065)

라이브러리: @dnd-kit/core

"use client";

import { DndContext, closestCenter, KeyboardSensor, PointerSensor, useSensor, useSensors } from "@dnd-kit/core";
import { SortableContext, sortableKeyboardCoordinates, useSortable, verticalListSortingStrategy } from "@dnd-kit/sortable";

export default function SortableTaskList({ tasks, onReorder }: Props) {
  const sensors = useSensors(
    useSensor(PointerSensor),
    useSensor(KeyboardSensor, {
      coordinateGetter: sortableKeyboardCoordinates,
    })
  );

  const handleDragEnd = (event: DragEndEvent) => {
    const { active, over } = event;
    if (over && active.id !== over.id) {
      onReorder(active.id, over.id);
    }
  };

  return (
    <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
      <SortableContext items={tasks.map(t => t.id)} strategy={verticalListSortingStrategy}>
        {tasks.map(task => (
          <SortableTaskItem key={task.id} task={task} />
        ))}
      </SortableContext>
    </DndContext>
  );
}

패턴: 드래그 앤 드롭에 @dnd-kit/core 사용, 드래그 종료 시 순서 변경 처리

2. 실행 취소/재실행 패턴(Phase 7 - T066)

"use client";

import { useReducer } from "react";

interface HistoryState<T> {
  past: T[];
  present: T;
  future: T[];
}

function historyReducer<T>(state: HistoryState<T>, action: { type: string; newPresent?: T }): HistoryState<T> {
  const { past, present, future } = state;

  switch (action.type) {
    case "UNDO":
      if (past.length === 0) return state;
      return {
        past: past.slice(0, past.length - 1),
        present: past[past.length - 1],
        future: [present, ...future],
      };
    case "REDO":
      if (future.length === 0) return state;
      return {
        past: [...past, present],
        present: future[0],
        future: future.slice(1),
      };
    case "SET":
      if (action.newPresent === present) return state;
      return {
        past: [...past, present],
        present: action.newPresent!,
        future: [],
      };
    default:
      return state;
  }
}

export function useHistory<T>(initialPresent: T) {
  const [state, dispatch] = useReducer(historyReducer, {
    past: [],
    present: initialPresent,
    future: [],
  });

  const undo = () => dispatch({ type: "UNDO" });
  const redo = () => dispatch({ type: "REDO" });
  const set = (newPresent: T) => dispatch({ type: "SET", newPresent });

  return { undo, redo, set, canUndo: state.past.length > 0, canRedo: state.future.length > 0, present: state.present };
}

패턴: useReducer를 사용한 히스토리 관리, UNDO/REDO/SET 액션 처리

3. 데이터 페칭 패턴(Phase 7 - T067)

// 서버 컴포넌트 (기본값)
import { getServerSession } from "next-auth";
import { TaskList } from "@/components/TaskList";

interface DashboardPageProps {
  searchParams: { filter?: string };
}

export default async function DashboardPage({ searchParams }: DashboardPageProps) {
  const session = await getServerSession();
  const tasks = await fetchTasks(session.user.id, searchParams.filter);

  return <TaskList tasks={tasks} />;
}

패턴:

  • Server Components에서 직접 데이터 페칭
  • 페이지/레이아웃에서 async 함수로 데이터 로드
  • 필요한 경우만 Client Components에 props로 전달
  • 검색 매개변수로 데이터 필터링 허용
  • 데이터는 서버에서만 가져오고, props로 클라이언트에 전달

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

ComeOnOliver/skillshub

Create stunning, animation-rich HTML presentations from scratch or by converting PowerPoint files. Use when the user wants to build a presentation, convert a PPT/PPTX to web, or create slides for a talk/pitch. Helps non-designers discover their aesthetic through visual exploration rather than abstract choices.

ComeOnOliver/skillshub

Next.js 16+ 和 Turbopack — 增量打包、文件系统缓存、开发速度,以及何时使用 Turbopack 与 webpack。

ComeOnOliver/skillshub

SwiftUI architecture patterns, state management with @Observable, view composition, navigation, performance optimization, and modern iOS/macOS UI best practices.

ComeOnOliver/skillshub

See, Understand, Act on video and audio. See- ingest from local files, URLs, RTSP/live feeds, or live record desktop; return realtime context and playable stream links. Understand- extract frames, build visual/semantic/temporal indexes, and search moments with timestamps and auto-clips. Act- transcode and normalize (codec, fps, resolution, aspect ratio), perform timeline edits (subtitles, text/image overlays, branding, audio overlays, dubbing, translation), generate media assets (image, audio, video), and create real time alerts for events from live streams or desktop capture.

ComeOnOliver/skillshub

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

ComeOnOliver/skillshub

Next.js 15 애플리케이션을 위한 프론트엔드 개발 가이드라인. React 19, TypeScript, Shadcn/ui, Tailwind CSS를 사용한 모던 패턴. Server Components, Client Components, App Router, 파일 구조, Shadcn/ui 컴포넌트, 성능 최적화, TypeScript 모범 사례 포함. 컴포넌트, 페이지, 기능 생성, 데이터 페칭, 스타일링, 라우팅, 프론트엔드 코드 작업 시 사용.

ComeOnOliver/skillshub

Provides Tamagui patterns for config v4, compiler optimization, styled context, and cross-platform styling. Must use when working with Tamagui projects (tamagui.config.ts, @tamagui imports).

ComeOnOliver/skillshub

Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.

ComeOnOliver/skillshub

Create high-converting, visually distinctive landing pages. Use when building marketing pages, product launches, SaaS homepages, or any single-page conversion-focused website. Guides section-by-section composition with anti-AI-slop principles.

ComeOnOliver/skillshub

Auto-loaded context for Portfolio Buddy 2 development. Use for ANY task involving: React 19 development, TypeScript, portfolio analysis features, metrics calculations, trading strategy comparison, or working with the Portfolio Buddy 2 codebase. Contains tech stack, known issues, and architectural constraints.

ComeOnOliver/skillshub

Next.js development tooling via MCP. Inspect routes, components, build info, and debug Next.js apps. Use when working on Next.js applications, debugging routing, or inspecting app structure. NOT for general React or non-Next.js projects.

ComeOnOliver/skillshub

Implement UI using Shadcn MCP (atoms/theme) and 21st.dev MCP (complex sections). Use when adding buttons, layouts, or generating landing pages.

ComeOnOliver/skillshub

A conceptual skill for building an API client in Next.js that handles JWT tokens

ComeOnOliver/skillshub

Best practices and patterns for Next.js App Router, Server Actions, and Routing in this project.

ComeOnOliver/skillshub

The Design System, Theme, and UX rules for the Physical AI Hub.

ComeOnOliver/skillshub

Comprehensive frontend development skill for building modern, performant web applications using ReactJS, NextJS, TypeScript, Tailwind CSS. Includes component scaffolding, performance optimization, bundle analysis, and UI best practices. Use when developing frontend features, optimizing performance, implementing UI/UX designs, managing state, or reviewing frontend code.

ComeOnOliver/skillshub

This document captures learnings from fixing keyboard navigation issues when floating components (Select, DropdownMenu, Popover) have CSS open/close animations.

ComeOnOliver/skillshub

Build Next.js 16 applications with correct patterns and distinctive design. Use when creating pages, layouts, dynamic routes, upgrading from Next.js 15, or implementing proxy.ts. Covers breaking changes (async params/searchParams, Turbopack, cacheComponents) and frontend aesthetics. NOT when building non-React or backend-only applications.

ComeOnOliver/skillshub

Comprehensive Framer Motion animation library for React. Covers motion components, variants, gestures, page transitions, and scroll animations. Use when adding animations to React/Next.js applications.

ComeOnOliver/skillshub

Build interfaces that resonate, not just render. This skill enforces bold, intentional

관련 스킬