Motion System v4.2
React / Next.js를 위한 프로덕션 레디 UI 모션 시스템.
성능, 접근성, 사용성에 초점을 맞춥니다 — 장식이 아닙니다.
사용 시기
이 모션 시스템은 다음과 같은 경우에 사용하세요:
- 주의를 안내할 때 (예: 온보딩, 주요 작업)
- 상태를 전달할 때 (로딩, 성공, 오류, 전환)
- 공간 연속성을 유지할 때 (레이아웃 변경, 네비게이션)
적절한 시나리오
- 인터랙티브 컴포넌트 (버튼, 모달, 메뉴)
- 상태 전환 (로딩 → 로드됨, 열림 → 닫힘)
- 네비게이션 및 레이아웃 연속성 (공유 요소, 크로스페이드)
고려 사항
- 접근성: 항상 reduced motion 지원
- 디바이스 적응: 저사양 기기에 맞게 조정
- 성능 트레이드오프: 시각적 부드러움보다 반응성 우선
모션을 사용하지 말아야 할 때
- 순전히 장식용일 때
- 사용성이나 명확성을 떨어뜨릴 때
- 성능에 부정적 영향을 미칠 때
작동 방식
핵심 원칙
모션은 반드시:
- 주의를 안내해야 함
- 상태를 전달해야 함
- 공간 연속성을 유지해야 함
위 중 어느 것도 해당하지 않으면 → 제거하세요.
설치
npm install motion
버전
motion/react- 최신 Motion for React 프로젝트 기본값 (패키지:motion)framer-motion- 여전히 Framer Motion에 의존하는 프로젝트를 위한 레거시 임포트 경로
혼용하지 마세요. 혼용하면 내부 스케줄러 충돌과 AnimatePresence 컨텍스트 손상이 발생하여, 한 패키지의 컴포넌트가 다른 패키지의 컴포넌트와 종료 애니메이션을 조정하지 못합니다.
프로젝트에서 사용 중인 버전을 확인하려면:
cat package.json | grep -E '"motion"|"framer-motion"'
항상 하나의 소스에서 일관되게 임포트하세요:
// 올바름 (모던)
import { motion, AnimatePresence } from "motion/react"
// 올바름 (레거시)
import { motion, AnimatePresence } from "framer-motion"
// 같은 프로젝트에서 절대 혼용하지 마세요
모션 토큰
// motionTokens.ts
export const motionTokens = {
duration: {
fast: 0.18,
normal: 0.35,
slow: 0.6
},
// `transition` 객체 내 `ease` 값으로 사용:
// transition={{ duration: motionTokens.duration.normal, ease: motionTokens.easing.smooth }}
easing: {
smooth: [0.22, 1, 0.36, 1] as [number, number, number, number],
sharp: [0.4, 0, 0.2, 1] as [number, number, number, number]
},
distance: {
sm: 8,
md: 16,
lg: 24
}
}
사용 예시:
import { motionTokens } from "@/lib/motionTokens"
<motion.div
initial={{ opacity: 0, y: motionTokens.distance.md }}
animate={{ opacity: 1, y: 0 }}
transition={{
duration: motionTokens.duration.normal,
ease: motionTokens.easing.smooth
}}
/>
성능 규칙
안전함
- transform
- opacity
피해야 할 것
- width / height
- top / left
규칙: 반응성 > 부드러움
디바이스 적응
휴리스틱은 CPU 코어 수 와 사용 가능한 메모리를 결합하여 더 신뢰할 수 있는 신호를 제공합니다. deviceMemory는 Chrome/Android에서 사용 가능하며, Safari와 Firefox를 위한 폴백이 포함되어 있습니다.
const isLowEnd =
typeof navigator !== "undefined" && (
// 낮은 메모리 (Chrome/Android 전용, 그 외는 undefined → 성능 좋은 것으로 간주)
(navigator.deviceMemory !== undefined && navigator.deviceMemory <= 2) ||
// 적은 코어 수 AND 메모리 API 없음 (약한 하드웨어의 Safari/Firefox 커버)
(navigator.deviceMemory === undefined && navigator.hardwareConcurrency <= 4)
)
const duration = isLowEnd ? 0.2 : 0.4
접근성
JS (useReducedMotion)
import { motion, useReducedMotion } from "motion/react"
export function FadeIn() {
const reduce = useReducedMotion()
return (
<motion.div
initial={{ opacity: 0, y: reduce ? 0 : 24 }}
animate={{ opacity: 1, y: 0 }}
/>
)
}
CSS
@media (prefers-reduced-motion: reduce) {
.motion-safe-transition {
transition: opacity 0.2s;
}
.motion-reduce-transform {
transform: none !important;
}
}
Tailwind
<div class="motion-safe:animate-fade motion-reduce:opacity-100"></div>
아키텍처 및 패턴
핵심 패턴
| 시나리오 | 패턴 |
|---|---|
| 호버 피드백 | whileHover |
| 탭 / 누름 피드백 | whileTap |
| 스크롤 시 표시 | whileInView |
| 스크롤 연결 값 | useScroll + useTransform |
| 조건부 마운트/언마운트 | AnimatePresence |
| 작은 레이아웃 이동 (단일 요소, ~300px 미만 변경) | layout prop |
| 큰 레이아웃 이동 또는 전체 페이지 리플로우 | layout 사용 금지; 대신 CSS 전환이나 페이지 수준 라우팅 사용 |
| 복잡한 명령형 시퀀스 | useAnimate |
큰 컨테이너에서
layout을 피해야 하는 이유? Framer의 레이아웃 애니메이션은transform을 사용하여 위치를 조정하지만, 전체 뷰포트를 차지하거나 깊은 리플로우를 유발하는 요소에서는 측정 비용으로 인해 눈에 띄는 버벅임과 CLS가 발생합니다. CSS Grid/Flexbox 전환을 선호하거나 특정 자식 요소에서만layoutId로 조정하세요.
레이아웃 및 전환
- 공유 요소 전환 →
layoutId(마운트된 인스턴스마다 고유해야 함) - 진입 / 종료 전환 →
AnimatePresence(아래mode지침 참조)
AnimatePresence mode
항상 mode를 명시적으로 지정하세요. 기본값("sync")은 진입과 종료를 동시에 실행하여 대부분의 UI 패턴에서 시각적 중첩을 유발합니다.
mode | 사용 시기 |
|---|---|
"wait" | 종료가 완료된 후 진입이 시작됨. 모달, 토스트, 페이지 전환에 사용. |
"sync" (기본값) | 진입과 종료가 중첩됨. 중첩이 의도적인 경우에만 사용 (예: 크로스페이드 캐러셀). |
"popLayout" | 종료 요소가 즉시 플로우에서 제거되고, 나머지 요소가 그 공간을 채움. 리스트, 탭, 닫을 수 있는 카드에 사용. |
// 모달 — 항상 "wait" 사용
<AnimatePresence mode="wait">
{open && <Modal key="modal" />}
</AnimatePresence>
// 닫을 수 있는 리스트 아이템 — "popLayout" 사용
<AnimatePresence mode="popLayout">
{items.map(item => <Card key={item.id} />)}
</AnimatePresence>
고급 패턴 (개념)
- 패럴랙스 (스크롤 연결 transform)
- 스크롤 스토리텔링 (고정 섹션)
- 3D 틸트 (포인터 기반 transform)
- 크로스페이드 (공유
layoutId) - 점진적 표시 (clip-path)
- 스켈레톤 로딩 (반복 opacity)
- 마이크로 인터랙션 (호버/탭 피드백)
- 스프링 시스템 (물리 기반 모션)
모달 필수 사항
- 포커스 트랩
- Escape 닫기
- 스크롤 잠금
- ARIA 역할
AnimatePresence mode="wait"사용하여 종료 애니메이션이 완료된 후 다음 모달이 진입하도록 함
전체 예제
import React, { useEffect, useRef, useState } from "react"
import { motion, AnimatePresence } from "motion/react"
function useFocusTrap(ref: React.RefObject<HTMLDivElement | null>, active: boolean) {
useEffect(() => {
if (!active || !ref.current) return
const el = ref.current
const focusable = el.querySelectorAll<HTMLElement>(
'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
)
const first = focusable[0]
const last = focusable[focusable.length - 1]
function handleKey(e: KeyboardEvent) {
if (e.key !== "Tab") return
if (e.shiftKey && document.activeElement === first) {
e.preventDefault()
last?.focus()
} else if (!e.shiftKey && document.activeElement === last) {
e.preventDefault()
first?.focus()
}
}
el.addEventListener("keydown", handleKey)
first?.focus()
return () => el.removeEventListener("keydown", handleKey)
}, [active, ref])
}
function useScrollLock(active: boolean) {
useEffect(() => {
if (!active) return
const prev = document.body.style.overflow
document.body.style.overflow = "hidden"
return () => { document.body.style.overflow = prev }
}, [active])
}
function Modal({ open, closeModal }: { open: boolean; closeModal: () => void }) {
const ref = useRef<HTMLDivElement>(null)
useFocusTrap(ref, open)
useScrollLock(open)
useEffect(() => {
function onKey(e: KeyboardEvent) {
if (e.key === "Escape") closeModal()
}
if (open) window.addEventListener("keydown", onKey)
return () => window.removeEventListener("keydown", onKey)
}, [open, closeModal])
return (
// mode="wait"는 종료 애니메이션이 완료된 후 새 모달이 진입하도록 보장
<AnimatePresence mode="wait">
{open && (
<motion.div
role="dialog"
aria-modal="true"
aria-labelledby="modal-title"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.2 }}
className="fixed inset-0 flex items-center justify-center bg-black/40"
>
<motion.div
ref={ref}
initial={{ scale: 0.95, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
exit={{ scale: 0.95, opacity: 0 }}
transition={{ duration: 0.2, ease: [0.22, 1, 0.36, 1] }}
className="bg-white p-6 rounded"
>
<h2 id="modal-title">Dialog Title</h2>
<button onClick={closeModal}>Close</button>
</motion.div>
</motion.div>
)}
</AnimatePresence>
)
}
export function Example() {
const [open, setOpen] = useState(false)
return (
<>
<button onClick={() => setOpen(true)}>Open</button>
<Modal open={open} closeModal={() => setOpen(false)} />
</>
)
}
SSR 안전성
- 서버와 클라이언트 렌더 간 초기 상태 일치
- 암시적 애니메이션 시작점 피하기 (항상
initial을 명시적으로 설정) - Next.js App Router에서 motion 컴포넌트를
"use client"로 감싸기
디버깅
확인:
- 잘못된 임포트 (
motion/react와framer-motion혼용) - Next.js App Router에서
"use client"지시문 누락 AnimatePresence자식에keyprop 누락- Hydration 불일치 (SSR과 클라이언트 간 초기 상태 다름)
- 큰 컨테이너에서
layoutprop 오용으로 인한 리플로우 버벅임 - 상태 기반 애니메이션이 트리거되지 않음 (의존성 배열 확인)
QA
- CLS 없음
- 키보드 작동
- 모달 내 포커스 트랩
- ARIA 역할 올바름 (
role="dialog",aria-modal="true") - Reduced motion 준수 (
useReducedMotion+ CSS 미디어 쿼리) - Next.js에서 hydration 경고 없음
- 언마운트 시 애니메이션 깔끔하게 중단 (메모리 누수 없음)
- 모든 사용 지점에서
AnimatePresence mode명시적 설정
안티 패턴
- 레이아웃 속성 애니메이션 (
width,height,top,left) - 목적 없는 무한 애니메이션 (항상 질문: 이 모션은 어떤 상태를 전달하는가?)
- 과도한 stagger (
staggerChildren≤ 0.1s 유지, 그 이상은 느리게 느껴짐) - reduced motion 선호 무시
- 크거나 전체 뷰포트 컨테이너에
layout사용 AnimatePresence에mode생략 (기본"sync"는 시각적 중첩 유발)- 순수 장식 목적으로 모션 사용
철학
모션은 인터랙션 디자인입니다.
최종 규칙
모션이 UX를 개선하지 않는다면 → 제거하세요.
예제
버튼 인터랙션
import { motion } from "motion/react"
export function Button() {
return (
<motion.button
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.97 }}
transition={{ duration: 0.15, ease: [0.4, 0, 0.2, 1] }}
>
Click me
</motion.button>
)
}
Reduced Motion 예제
import { motion, useReducedMotion } from "motion/react"
export function FadeIn() {
const reduce = useReducedMotion()
return (
<motion.div
initial={{ opacity: 0, y: reduce ? 0 : 24 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: reduce ? 0.1 : 0.35, ease: [0.22, 1, 0.36, 1] }}
/>
)
}
Stagger 리스트
import { motion } from "motion/react"
const container = {
hidden: {},
visible: {
transition: { staggerChildren: 0.08 } // 지연 없음 방지를 위해 ≤ 0.1s 유지
}
}
const item = {
hidden: { opacity: 0, y: 10 },
visible: { opacity: 1, y: 0, transition: { duration: 0.3, ease: [0.22, 1, 0.36, 1] } }
}
export function List() {
return (
<motion.ul variants={container} initial="hidden" animate="visible">
{[1, 2, 3].map(i => (
<motion.li key={i} variants={item}>Item {i}</motion.li>
))}
</motion.ul>
)
}
AnimatePresence를 사용한 모달
import { motion, AnimatePresence } from "motion/react"
export function Modal({ open }: { open: boolean }) {
return (
<AnimatePresence mode="wait">
{open && (
<motion.div
initial={{ opacity: 0, scale: 0.95 }}
animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, scale: 0.95 }}
transition={{ duration: 0.2, ease: [0.22, 1, 0.36, 1] }}
/>
)}
</AnimatePresence>
)
}
스크롤 패럴랙스
import { useScroll, useTransform, motion } from "motion/react"
export function Parallax() {
const { scrollYProgress } = useScroll()
const y = useTransform(scrollYProgress, [0, 1], [0, -80])
return <motion.div style={{ y }} />
}
스켈레톤 로딩
import { motion } from "motion/react"
export function Skeleton() {
return (
<motion.div
className="bg-gray-200 h-6 w-full rounded"
animate={{ opacity: [0.5, 1, 0.5] }}
transition={{
duration: 1.5, // 편안한 펄스 — 없으면 빠른 플래시 발생
repeat: Infinity,
ease: "easeInOut"
}}
/>
)
}
공유 레이아웃 (크로스페이드)
import { motion } from "motion/react"
// layoutId는 마운트된 인스턴스마다 고유해야 합니다.
// 여러 인스턴스가 동시에 존재할 수 있는 경우 고유 id를 추가하세요:
// layoutId={`shared-${item.id}`}
export function Shared() {
return <motion.div layoutId="shared" />
}