Communitygithub.com

페이지 전환 애니메이션 (Next.js App Router)

Next.js App Router에서 페이지 진입/퇴장 전환 애니메이션을 구현하고, Framer Motion AnimatePresence의 퇴장 애니메이션이 라우트 변경 시 작동하지 않는 문제를 해결합니다.

페이지 전환 애니메이션 (Next.js App Router)란 무엇인가요?

이 스킬은 Next.js App Router에서 페이지 전환 애니메이션을 구현하는 방법을 상세히 설명합니다. 특히 Framer Motion의 `AnimatePresence`가 라우트 변경 시 퇴장 애니메이션을 실행하지 못하는 가장 흔한 문제의 근본 원인과 두 가지 해결 방법을 제시합니다. 첫 번째 방법은 `template.tsx`에 키가 지정된 `AnimatePresence`와 `FrozenRouter` 패턴을 결합하여 퇴장 애니메이션이 올바르게 실행되도록 하는 것이고, 두 번째 방법은 기본 View Transitions API 또는 `next-view-transitions` 라이브러리를 사용하는 것입니다. 또한 애니메이션이 작동하지 않을 때 확인해야 할 디버그 체크리스트와 독립형 HTML 파일로 애니메이션을 검증하는 방법을 제공합니다.

지원 대상~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/nehakanjamala/personal_website/tree/HEAD/.agents/skills/page-transition-animation

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

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

문서

페이지 전환 애니메이션 (Next.js App Router)은(는) 무엇을 하나요?

Next.js App Router에서 페이지 진입/퇴장 전환을 구현하고, 가장 흔한 실패인 Framer Motion AnimatePresence 퇴장 애니메이션이 네비게이션 시 실행되지 않는 문제를 해결합니다. 원인은 구조적입니다. App Router에서 네비게이션 시 Next.js는 이전 라우트의 콘텐츠를 언마운트하고 새 라우트의 콘텐츠를 거의 즉시 마운트합니다. AnimatePresence는 퇴장하는 요소가 마운트된 상태로 유지되면서 지속적인 AnimatePresence 래퍼 아래에서 애니메이션이 실행될 시간을 충분히 가져야만 퇴장을 애니메이션할 수 있습니다. 라우터가 그 아래에서 자식 요소를 교체하기 때문에 퇴장은 건너뛰어집니다. 두 가지 접근 방식으로 이 문제를 해결합니다: pathname을 키로 사용하는 AnimatePresence와 FrozenRouter 패턴을 사용하거나 View Transitions API (네이티브 / next-view-transitions)를 사용합니다.

사용 시기

Next.js App Router 앱에서 애니메이션 페이지 전환을 추가할 때, Framer Motion exit prop이 라우트 변경 시 아무 효과가 없을 때, 이전 페이지가 애니메이션 없이 즉시 사라질 때, Next.js에 Framer Motion과 View Transitions API 중 선택해야 할 때, 또는 라우트 간 AnimatePresence가 작동하지 않는 이유를 디버깅할 때 사용합니다.

퇴장이 실행되지 않는 이유 (핵심 문제)

AnimatePresence는 직접적인 키가 있는 자식의 제거를 감지합니다. App Router 네비게이션에서:

  1. 래퍼는 네비게이션 전반에 걸쳐 지속되어야 합니다. AnimatePresence가 스스로 언마운트되는 컴포넌트에 있다면 퇴장을 실행할 것이 아무것도 남지 않습니다.
  2. AnimatePresence가 "이전 것은 제거되고 새 것이 추가됨"을 인식할 수 있도록 자식의 key는 라우트별로 변경되어야 합니다.
  3. 짧은 중첩 기간 동안 나가는 서브트리는 여전히 이전 콘텐츠를 렌더링해야 하지만, App Router는 이미 라우트 컨텍스트를 교체했으므로 나가는 트리는 그렇지 않으면 새 페이지의 데이터를 렌더링할 것입니다. 이것이 바로 FrozenRouter가 해결하는 부분입니다.

해결책 A: template.tsx + 키가 있는 AnimatePresence + FrozenRouter

template.tsx는 이를 위해 App Router가 제공하는 목적에 맞는 훅입니다. (지속되는) layout.tsx와 달리 template은 모든 네비게이션에서 다시 마운트되어 각 라우트에 새 인스턴스를 제공합니다. 라우트별 진입 애니메이션에 이상적입니다. pathname을 키로 사용하는 AnimatePresence와 FrozenRouter를 결합하여 깔끔한 퇴장 + 진입을 구현합니다.

// app/template.tsx
'use client';
import { AnimatePresence } from 'framer-motion';
import { usePathname } from 'next/navigation';
import { FrozenRouter } from './frozen-router';
import { PageTransition } from './page-transition';

export default function Template({ children }: { children: React.ReactNode }) {
  const pathname = usePathname();
  return (
    <AnimatePresence mode="wait" initial={false}>
      {/* key를 pathname으로 설정하여 AnimatePresence가 이전 것은 제거되고 새 것이 추가됨을 인식하게 함 */}
      <PageTransition key={pathname}>
        {/* FrozenRouter는 나가는 트리가 퇴장 애니메이션을 실행하는 동안
            이전 콘텐츠를 계속 렌더링하도록 유지함 */}
        <FrozenRouter>{children}</FrozenRouter>
      </PageTransition>
    </AnimatePresence>
  );
}
// app/page-transition.tsx
'use client';
import { motion } from 'framer-motion';

export function PageTransition({ children }: { children: React.ReactNode }) {
  return (
    <motion.div
      initial={{ opacity: 0, y: 12 }}
      animate={{ opacity: 1, y: 0 }}
      exit={{ opacity: 0, y: -12 }}
      transition={{ duration: 0.3, ease: [0.22, 1, 0.36, 1] }}
    >
      {children}
    </motion.div>
  );
}
// app/frozen-router.tsx
'use client';
import { useContext, useRef } from 'react';
import {
  LayoutRouterContext,
} from 'next/dist/shared/lib/app-router-context.shared-runtime';

// 라우터 컨텍스트를 고정하여 퇴장 애니메이션 중에
// 나가는 페이지가 다음 라우트의 콘텐츠 대신 자신의 콘텐츠를 계속 렌더링하도록 함
export function FrozenRouter({ children }: { children: React.ReactNode }) {
  const context = useContext(LayoutRouterContext ?? {});
  const frozen = useRef(context).current;

  return (
    <LayoutRouterContext.Provider value={frozen}>
      {children}
    </LayoutRouterContext.Provider>
  );
}

함께 작동하는 방식:

  • mode="wait"는 AnimatePresence가 새 페이지를 마운트하기 전에 퇴장을 완전히 끝내도록 합니다. (진입/퇴장이 중첩/크로스페이드되어야 하는 경우 기본 모드를 사용하십시오.)
  • initial={false}는 첫 로드 시 진입 애니메이션을 건너뜁니다. (선택 사항)
  • key={pathname}은 AnimatePresence가 각 라우트를 별개의 존재로 취급하도록 만듭니다.
  • FrozenRouter는 LayoutRouterContext를 스냅샷하여 나가는 서브트리가 퇴장 내내 이전 라우트의 콘텐츠를 렌더링하고, 새 라우트의 콘텐츠를 깜박이지 않도록 합니다. 이것이 없으면 퇴장이 건너뛰거나 잘못된 콘텐츠를 표시합니다.

참고: LayoutRouterContext는 Next.js 내부 요소입니다. import 경로는 Next 버전 간에 변경될 수 있습니다. 업그레이드 후 import가 깨지면 해당 경로를 업데이트하십시오.

해결책 B: 네이티브 View Transitions API

View Transitions API는 브라우저가 전후 스냅샷을 캡처하여 두 DOM 상태 간에 애니메이션을 적용합니다. 요소별 퇴장 컴포넌트가 필요 없습니다.

/* globals.css */
@view-transition { navigation: auto; } /* 지원되는 곳에서 MPA 스타일 사용 */

::view-transition-old(root) { animation: fade 0.25s both reverse; }
::view-transition-new(root) { animation: fade 0.25s both; }
@keyframes fade { from { opacity: 0; } to { opacity: 1; } }

SPA 스타일 App Router 네비게이션의 경우 라우터 업데이트를 감싸십시오:

if (document.startViewTransition) {
  document.startViewTransition(() => router.push(href));
} else {
  router.push(href);
}

next-view-transitions 라이브러리

next-view-transitions는 View Transitions API를 App Router의 클라이언트 네비게이션과 통합하여 즉시 사용 가능하게 합니다:

// app/layout.tsx
import { ViewTransitions } from 'next-view-transitions';
export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <ViewTransitions>
      <html lang="ko"><body>{children}</body></html>
    </ViewTransitions>
  );
}
// next/link 대신 라이브러리의 Link 사용
import { Link } from 'next-view-transitions';
<Link href="/about">소개</Link>;

간단한 페이지 간 페이드/모프 및 공유 요소 전환에는 View Transitions를 선택하고, 세밀하고 조율 가능하며 중단 가능하거나 지연된 퇴장 애니메이션이 필요할 때는 Framer Motion을 선택하십시오. View Transitions API 브라우저 지원은 아직 고르지 않으므로 적절한 폴백(if (document.startViewTransition) 가드)을 제공하십시오.

AnimatePresence 디버그 체크리스트

퇴장이 여전히 작동하지 않을 때 순서대로 확인하십시오:

  1. 래퍼가 마운트된 상태로 유지됩니다. AnimatePresence는 지속적인 무언가에 있어야 합니다. 이상적으로는 template.tsx 또는 레이아웃 수준의 클라이언트 컴포넌트여야 하며, 언마운트되는 페이지 내부에 있으면 안 됩니다.
  2. 안정적이고 변경되는 키. 애니메이션 대상 자식은 key={pathname} (또는 유사한 것)이 필요하여 제거가 감지됩니다. 키가 없거나 변경되지 않는 키가 있으면 퇴장이 실행되지 않습니다.
  3. 직접적인 motion 하위 요소. exit prop이 있는 요소는 motion.* 컴포넌트이면서 AnimatePresence의 자식이어야 합니다 (중간에 non-motion 래퍼가 있으면 감지를 차단할 수 있습니다).
  4. mode="wait" 이전 것과 새 것이 중첩되지 않아야 하는 경우 사용합니다. 없으면 둘 다 동시에 렌더링되어 튀는 현상이 발생할 수 있습니다.
  5. FrozenRouter가 있어야 합니다. 나가는 페이지가 퇴장 중에 새 라우트의 콘텐츠를 깜박이는 경우에 필요합니다.
  6. 'use client' AnimatePresence/usePathname/motion을 사용하는 모든 파일에 필요합니다.
  7. mode="wait"에서 한 번에 하나의 자식만 있어야 합니다. AnimatePresence는 교체할 하나의 키가 있는 존재를 예상합니다.

전달 및 검증 (독립형 HTML)

패키징된 도우미 (scripts/): scripts/seek-shot.sh anim.html 0 1.5 3 명령어는 ?t=N 하네스를 고정하고 각 순간을 스크린샷으로 캡처합니다. scripts/contact-sheet.sh sheet.png frame-*.png 명령어는 한눈에 검토할 수 있도록 타일로 배열합니다. scripts/README.md를 참조하십시오.

실제 대상은 Next.js 앱이지만, 전환 형태 (진입/퇴장 곡선, 방향, 크로스페이드)를 증명하기 위해 브라우저에서 직접 열리는 하나의 HTML 파일을 제공할 수 있습니다. CDN의 motion 또는 네이티브 View Transitions API를 사용해 애니메이션되는 토글 가능한 두 개의 스텁 "페이지"가 포함됩니다. 하나의 파일로 라우터를 연결하기 전에 모션을 검증하기에 적절한 수준입니다. 페이드 하나를 확인하기 위해 Next를 설정할 필요는 없습니다.

출력 계약:

  • 하나의 .html 파일: 두 개의 뷰 스텁과 토글, CDN에서 motion/React를 가져오는 인라인 <script type="module"> 또는 document.startViewTransition + ::view-transition-* CSS로 애니메이션됩니다.
  • 해결된 최종 상태를 고정하는 방법: 라우트 전환은 상태 기반(어떤 뷰, 교체 중간)이므로, 시간이 아닌 상태를 스크린샷으로 캡처합니다.

시크 하네스 — 전환 단계 고정. ?view=b는 대상 뷰를 마운트하고 (또는 ?phase=exit는 나가는 트리를 애니메이션 중간에 고정) 스크린샷이 고정된 단계를 캡처하도록 합니다:

<script>
  const p = new URLSearchParams(location.search);
  document.documentElement.dataset.view = p.get("view") || "a";   // CSS/React는 이를 기반으로 함
  // Framer Motion: ?view에서 제어된 key/route 설정; mode="wait"의 경우 해결된 끝은 새 페이지
  // View Transitions: END 상태 스크린샷(스냅샷은 일시적임); 또는 느린 애니메이션 에뮬레이션을 통해 일시 중지
  window.__ready = true;
</script>

검증 루프 — 렌더링 → 단계 설정 → 스크린샷 → 확인: 소스, 중간, 대상 (?view=a, ?phase=exit, ?view=b)을 열고 각각 스크린샷을 캡처한 후 충실도 (퇴장이 실제로 실행되는지, 방향/크로스페이드가 요구 사항과 일치하는지, mode="wait" 지연이 없는지)와 아티팩트 (나가는 트리가 새 페이지의 콘텐츠를 깜박이는지, 이중 마운트, FOUC, 버벅임)를 확인합니다. 모든 헤드리스 도구가 작동합니다:

npx playwright screenshot --wait-for-timeout=500 "file://$PWD/transition.html?view=b" dest.png

완료 전 확인 사항:

  1. 독립적으로 열림 — 콘솔 오류 없음, CDN motion/React (사용된 경우) 정상 로드, startViewTransition 가드 처리됨.
  2. ?view=/?phase= 고정이 결정적인 전환 단계를 캡처함.
  3. 소스 / 중간 / 대상에서 스크린샷이 찍힘 — 요구 사항과 일치, 콘텐츠 플래시 또는 퇴장 누락 없음.
  4. prefers-reduced-motion 준수 — 슬라이드/이동이 짧은 크로스페이드로 대체됨.
  5. 이징이 의도적임 — 진입은 ease-out, 퇴장은 ease-in, 지속 시간 ~0.2–0.4초 (mode="wait"에서 느리지 않음).

빠른 참조

필요 사항접근 방식
라우트별 진입 애니메이션app/template.tsx (네비게이션마다 다시 마운트)
네비게이션 시 퇴장 애니메이션키가 있는 AnimatePresence mode="wait" + FrozenRouter
나가는 페이지가 이전 콘텐츠를 표시함FrozenRouter (LayoutRouterContext 스냅샷)
라우트 변경 감지usePathname()을 key로 사용
간단한 페이지 간 페이드/모프View Transitions API / next-view-transitions
공유 요소 전환view-transition-name CSS
첫 로드 애니메이션 건너뛰기initial={false}

주의 사항

  • layout.tsx는 지속되며 라우트별로 다시 마운트되지 않습니다 — 라우트별 진입 애니메이션에는 template.tsx를 사용하십시오.
  • FrozenRouter를 생략하면 퇴장 중인 페이지가 새 라우트의 콘텐츠를 렌더링하여 (눈에 띄게 깜박임) 퇴장이 완전히 건너뛸 수 있습니다.
  • LayoutRouterContext import 경로는 Next 내부 요소입니다. 버전 간에 변경될 수 있으며, 업그레이드 후 가장 먼저 수정해야 할 사항입니다.
  • key={pathname}이 없으면 AnimatePresence는 동일한 자식을 보고 퇴장을 절대 트리거하지 않습니다.
  • mode="wait"는 진입 전에 퇴장을 기다립니다. 느린 퇴장에 과도하게 사용하면 네비게이션이 느리게 느껴질 수 있습니다. 지속 시간을 조정하십시오 (~0.2-0.4초).
  • View Transitions API는 완전한 브라우저 지원이 부족합니다. 항상 document.startViewTransition을 가드하십시오.
  • 모든 전환 파일에는 'use client'가 필요합니다. 서버 컴포넌트는 AnimatePresence/usePathname을 사용할 수 없습니다.

참조 파일

  • references/full-examples.md — 방향성/슬라이드 전환, view-transition-name을 사용한 공유 요소 View Transitions, mode="wait"가 아닌 크로스페이드 변형, loading.tsx를 사용한 로딩 상태 전환, 그리고 완전히 작동하는 App Router 폴더 레이아웃이 포함되어 있습니다.

Individual skills in this repo

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

nehakanjamala/personal_website

This skill should be used when the user asks to "fix janky CSS animation", "make animation 60fps", "stop layout thrashing", "animate width/height/top/left smoothly", "convert animation to transform", "animate box-shadow performantly", "animate height auto", "FLIP animation", or "why is my scroll/hover animation choppy".

nehakanjamala/personal_website

This skill should be used when the user asks to "respect prefers-reduced-motion", "honor reduced motion", "make my animations accessible", "fix vestibular / motion-sickness issues", "add a useReducedMotion hook", "gate GSAP / Framer Motion / Lenis for reduced motion", or "meet WCAG 2.3.3 / C39". Provides tiered (not all-or-nothing) reduced-motion patterns in CSS and JS.

nehakanjamala/personal_website

Create, modify, debug, and deploy Apify Actors, and write their input and output schemas. Use when building an Actor from scratch, changing or troubleshooting Actor code, generating or updating .actor schema files, or pushing an Actor to the Apify platform. To wrap an existing non-Actor project, use apify-actorization instead.

nehakanjamala/personal_website

Convert existing projects into Apify Actors - serverless cloud programs. Actorize JavaScript/TypeScript (SDK with Actor.init/exit), Python (async context manager), or any language (CLI wrapper). Use when migrating code to Apify, wrapping CLI tools as Actors, or adding Actor SDK to existing projects.

nehakanjamala/personal_website

Deprecated. Output schema generation moved to the apify-actor-development skill; prefer that skill whenever it is available.

nehakanjamala/personal_website

Design and build an official Apify integration for a company's product - workflow-automation apps (Zapier/n8n-style), AI agent plugins (coding-agent skills+MCP bundles or OpenClaw/Hermes-style harnesses), AI framework packages (LangChain/LlamaIndex-style), or direct application clients via apify-client. Use when planning, creating, or reviewing an integration that exposes Apify Actors, runs, datasets, or key-value stores inside another product.

nehakanjamala/personal_website

Universal AI-powered web scraper for any platform. Scrape data from Instagram, Facebook, TikTok, YouTube, LinkedIn, X/Twitter, Google Maps, Google Search, Google Trends, Reddit, Airbnb, Yelp, and 15+ more platforms. Use for lead generation, brand monitoring, competitor analysis, influencer discovery, trend research, content analytics, audience analysis, review analysis, SEO intelligence, recruitment, or any data extraction task.

nehakanjamala/personal_website

This skill should be used when the user asks to "add a glassmorphism effect", "frosted glass UI", "Apple liquid glass style", "frosted blur card", "translucent glass panel animation", "make a frosted nav bar", "build a glass modal/dialog", "animate a glass card on hover", or "add a refracting liquid-glass hero". Covers frosted translucent panels with backdrop-filter blur, edge/specular highlights, SVG liquid-glass refraction, motion on hover/scroll/enter, and accessible reduced-transparency fallbacks.

nehakanjamala/personal_website

This skill should be used when the user asks to "build a scroll animation", "add ScrollTrigger", "pin a section while scrolling", "scrub an animation to scroll", "create a hero timeline", "do a horizontal scroll section", "split text and animate words", "animate a layout change with GSAP Flip", "sync ScrollTrigger with Lenis", "Lenis smooth scroll jittery", "ScrollTrigger markers drift", "ScrollTrigger pins break with Lenis/Locomotive", or "set up smooth scroll with GSAP pinning". Covers GSAP timelines, ScrollTrigger, SplitText, Flip, and Lenis/Locomotive smooth-scroll sync for code-driven web motion.

nehakanjamala/personal_website

This skill should be used when the user asks to "add a Lottie animation", "play a .lottie or .json animation", "integrate a Bodymovin/After Effects animation on web or mobile", "control Lottie playback / segments", "make a scroll-driven Lottie", "recolor a Lottie at runtime", or "export an AE animation to Lottie". Covers dotLottie/lottie-web integration, playback control, interactivity, theming, and the AE export checklist.

nehakanjamala/personal_website

This skill should be used when the user asks to "add a hover/press effect", "animate a toggle or switch", "build an animated like button", "make a toast/snackbar slide in", "animate a drawer or modal", "animate list reordering or add/remove", "do a shared-element layout transition", or "polish UI feedback". Covers UI motion with Framer Motion (motion/react) and modern CSS.

nehakanjamala/personal_website

Scrape web pages using Scrapling with anti-bot bypass (like Cloudflare Turnstile), stealth headless browsing, spiders framework, adaptive scraping, and JavaScript rendering. Use when asked to scrape, crawl, or extract data from websites; web_fetch fails; the site has anti-bot protections; write Python code to scrape/crawl; or write spiders.

nehakanjamala/personal_website

This skill should be used when the user asks to "animate an SVG", "make a line draw itself on", "do a stroke draw-on / signature animation", "morph one shape into another", "move an element along a path", "animate an icon/logo", or "animate an SVG gradient or filter". Covers stroke-dashoffset draw-on, path morphing, motion-along-path, and animated icons/gradients/filters via CSS, SMIL, and GSAP.

관련 스킬