Framer Motion & UI Animation
Framer Motion으로 React 애니메이션 마스터하기: 제스처, 드래그, 레이아웃 애니메이션, 페이지 전환, 그리고 성능 최적화.
Motion 컴포넌트 기초
Framer Motion의 핵심 구성 요소 이해하기
motion.div란 무엇인가?
Motion 컴포넌트
Framer Motion의 기본 단위는 motion 컴포넌트입니다. 이는 모든 HTML 엘리먼트를 감싸서 React state와 매끄럽게 통합되는 선언적 애니메이션을 가능하게 합니다.
- 선언적: 무엇을 정의하지, 어떻게가 아닙니다
- State 기반: 애니메이션이 React state 변경에 반응합니다
- 조합 가능: 복잡한 애니메이션을 위해 Variants와 함께 작동합니다
기본 애니메이션 속성
import { motion } from "framer-motion";
<motion.div
initial={{ opacity: 0, y: 20 }} // Starting state
animate={{ opacity: 1, y: 0 }} // End state
transition={{ duration: 0.4 }} // How to animate
/>
// Key properties:
// - initial: Animation starting point
// - animate: Target animation state
// - transition: Timing and easing configuration
// - exit: Animation when component unmounts인터랙티브 데모
참고: 이 간단한 토글은 exit 애니메이션을 하지 않습니다. exit 애니메이션을 위해서는 AnimatePresence가 필요합니다 (나중에 다룹니다).
애니메이션 가능한 속성
Transform
x, y, scale, rotate, skew
Visual
opacity, color, backgroundColor
Layout
width, height, borderRadius
Filter
blur, brightness, contrast
성능 팁
Transform 속성 (x, y, scale, rotate)은 GPU 가속되며 레이아웃 재계산을 유발하지 않습니다. 더 나은 성능을 위해 width/height보다 이를 선호하세요.
Variants
복잡한 오케스트레이션을 위한 state 기반 애니메이션 패턴
Variants란 무엇인가?
Variants 개념
Variants는 문자열로 참조할 수 있는 이름이 지정된 애니메이션 state입니다. 이는 다음을 가능하게 합니다:
- 재사용성: 한 번 정의하고, 어디서나 사용
- 전파: 자식 컴포넌트가 부모 state를 상속
- 오케스트레이션: 애니메이션을 시차, 지연, 순서화
기본 Variants 패턴
const boxVariants = {
hidden: { opacity: 0, y: 20 },
show: { opacity: 1, y: 0 },
};
<motion.div
variants={boxVariants}
initial="hidden"
animate="show"
/>
// Instead of inline objects,
// you reference states by name!Stagger Children
const container = {
hidden: { opacity: 0 },
show: {
opacity: 1,
transition: {
staggerChildren: 0.1, // 100ms delay between children
},
},
};
const item = {
hidden: { opacity: 0, y: 20 },
show: { opacity: 1, y: 0 },
};
<motion.ul variants={container} initial="hidden" animate="show">
{items.map((item) => (
<motion.li variants={item} key={item.id}>
{item.text}
</motion.li>
))}
</motion.ul>Variant 전파
전파 작동 방식
부모 컴포넌트가 새로운 variant로 변경되면, 동일한 variant 이름을 가진 모든 자식이 자동으로 일치하도록 애니메이션됩니다. 이는 명시적인 연결 없이 조정된 애니메이션을 생성합니다.
// Parent controls the animation state
<motion.div
initial="rest"
whileHover="hover"
variants={parentVariants}
>
{/* Children automatically inherit "rest" → "hover" */}
<motion.span variants={childVariants}>
Icon
</motion.span>
<motion.span variants={childVariants}>
Label
</motion.span>
</motion.div>
// No need to add whileHover to each child!오케스트레이션 옵션
staggerChildren
각 자식 애니메이션 시작 사이의 지연
staggerDirection
1 = 처음부터 끝까지, -1 = 끝에서 처음까지
delayChildren
자식 애니메이션 시작 전 대기
when
"beforeChildren" | "afterChildren"
제스처 기반 상호작용
hover, tap, focus, scroll 애니메이션으로 반응형 UI 만들기
제스처 Props 개요
사용 가능한 제스처 Props
- whileHover: 마우스 hover 시 애니메이션
- whileTap: 누르거나 클릭하는 동안 애니메이션
- whileFocus: 엘리먼트에 포커스가 있을 때 애니메이션
- whileInView: 엘리먼트가 뷰포트에 진입할 때 애니메이션
- whileDrag: 드래그하는 동안 애니메이션
Hover & Tap
<motion.button
whileHover={{ scale: 1.05 }}
whileTap={{ scale: 0.95 }}
transition={{ type: "spring", stiffness: 400 }}
>
Click Me
</motion.button>
// Combines multiple gestures for
// a polished interaction feelwhileInView (스크롤 애니메이션)
<motion.div
initial={{ opacity: 0, y: 50 }}
whileInView={{ opacity: 1, y: 0 }}
viewport={{ once: true, margin: "-100px" }}
transition={{ duration: 0.5 }}
>
Appears when scrolled into view
</motion.div>
// viewport options:
// - once: Only animate first time
// - margin: Trigger offset from edge
// - amount: Percentage visible (0-1)첫 번째 아이템
두 번째 아이템
세 번째 아이템
포커스 State
<motion.input
whileFocus={{ scale: 1.02, borderColor: "#3B82F6" }}
transition={{ duration: 0.2 }}
className="border-2 px-4 py-2 rounded"
placeholder="Focus me"
/>제스처 이벤트 핸들러
이벤트 콜백
Framer Motion은 제스처 이벤트에 대한 콜백을 제공합니다:
<motion.div
onHoverStart={() => console.log("Hover started")}
onHoverEnd={() => console.log("Hover ended")}
onTapStart={() => console.log("Tap started")}
onTap={() => console.log("Tapped")}
onTapCancel={() => console.log("Tap cancelled")}
onPan={(e, info) => console.log(info.offset)}
/>Drag & Drop
물리 기반 상호작용으로 드래그 가능한 UI 컴포넌트 구축
기본 드래그
<motion.div drag>
Drag me anywhere!
</motion.div>
// Or constrain to an axis:
<motion.div drag="x">Horizontal only</motion.div>
<motion.div drag="y">Vertical only</motion.div>드래그 제약
// Using pixel values
<motion.div
drag
dragConstraints={{
top: -50,
left: -50,
right: 50,
bottom: 50,
}}
/>
// Or reference a parent element
const constraintsRef = useRef(null);
<motion.div ref={constraintsRef}>
<motion.div drag dragConstraints={constraintsRef} />
</motion.div>드래그 옵션
dragElastic
0 = 강한 제약, 1 = 완전한 탄성 (기본값: 0.5)
dragMomentum
속도에 따라 릴리스 후 계속 이동 (기본값: true)
dragTransition
모멘텀 애니메이션 구성: bounceStiffness, bounceDamping
dragDirectionLock
임계값 후 감지된 방향으로 잠금
모멘텀이 있는 드래그
수평으로 스와이프하고 릴리스하여 모멘텀 확인
사용 사례
일반적인 응용
- Kanban 보드: 열 사이에서 카드 드래그 (Trello)
- 캐러셀: 스와이프 기반 이미지 갤러리
- 슬라이더: 커스텀 범위 입력
- 재정렬 가능한 리스트: 아이템을 드래그하여 재정렬
- 닫을 수 있는 아이템: 스와이프하여 알림 삭제
// Swipe to dismiss pattern
<motion.div
drag="x"
dragConstraints={{ left: 0, right: 0 }}
onDragEnd={(e, { offset, velocity }) => {
if (Math.abs(offset.x) > 200 || Math.abs(velocity.x) > 500) {
onDismiss();
}
}}
>
Swipe to dismiss
</motion.div>레이아웃 애니메이션
레이아웃 변경 시 자동 부드러운 전환
layout Prop의 마법
레이아웃 애니메이션이 하는 일
layout prop을 추가하면, Framer Motion은 성능이 좋은 transforms를 사용하여 레이아웃 변경(위치, 크기) 사이를 자동으로 애니메이션합니다. 이것은 CSS만으로는 거의 불가능한 일입니다.
// Just add layout prop - that's it!
<motion.div layout>
{isExpanded ? "Large content here" : "Small"}
</motion.div>
// The element smoothly animates between
// any size/position changes automatically아코디언 예제
클릭하세요!
리스트 재정렬
// Each item needs layout prop
{items.map((item) => (
<motion.div
key={item.id}
layout
onClick={() => removeItem(item.id)}
>
{item.text}
</motion.div>
))}
// When items are removed, remaining items
// smoothly slide into their new positions그리드 ↔ 리스트 토글
레이아웃 Prop 옵션
layout
위치와 크기 변경 모두 애니메이션
layout="position"
크기가 아닌 위치만 애니메이션 (텍스트 왜곡 방지)
layout="size"
위치가 아닌 크기 변경만 애니메이션
layoutId="shared-id"
다른 컴포넌트 간 공유 레이아웃 애니메이션
AnimatePresence
컴포넌트가 마운트 및 언마운트될 때 애니메이션
문제점
왜 AnimatePresence인가?
React는 언마운트될 때 DOM에서 엘리먼트를 즉시 제거합니다. 이는 AnimatePresence 없이는 exit 애니메이션이 불가능함을 의미하며, 이는 exit 애니메이션 동안 엘리먼트를 DOM에 유지합니다.
기본 사용법
import { AnimatePresence, motion } from "framer-motion";
<AnimatePresence>
{isVisible && (
<motion.div
key="unique-key"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
>
I will fade out when removed!
</motion.div>
)}
</AnimatePresence>
// Key points:
// 1. Wrap conditional content in AnimatePresence
// 2. Add exit prop to define exit animation
// 3. Always provide a unique key모달 예제
Toast 알림
AnimatePresence 모드
mode="sync" (기본값)
Enter와 exit 애니메이션이 동시에 발생
mode="wait"
enter하기 전에 exit가 완료될 때까지 대기 (페이지 전환에 좋음)
mode="popLayout"
Exit하는 엘리먼트가 즉시 레이아웃 플로우에서 제거됨
// Page transition pattern
<AnimatePresence mode="wait">
<motion.div
key={router.pathname}
initial={{ opacity: 0, x: 20 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: -20 }}
>
<Component {...pageProps} />
</motion.div>
</AnimatePresence>사용 사례
일반적인 응용
- 모달 & 다이얼로그: Fade/scale in 및 out
- Toast 알림: Slide in 및 dismiss
- 드롭다운: 메뉴 확장 및 축소
- 페이지 전환: 라우트 간 크로스페이드
- 아코디언: 부드러운 콘텐츠 reveal
전환 & Springs
springs, tweens, keyframes로 애니메이션 타이밍 미세 조정
Spring 물리 (기본값)
왜 Springs인가?
Framer Motion은 더 자연스럽고 반응적인 애니메이션을 생성하기 때문에 기본적으로 spring 물리를 사용합니다. 지속 시간 기반 tweens와 달리, springs는 중단에 부드럽게 반응합니다.
// Spring parameters
transition={{
type: "spring",
stiffness: 100, // Higher = snappier (default: 100)
damping: 10, // Higher = less bounce (default: 10)
mass: 1, // Higher = slower, more momentum
velocity: 0, // Initial velocity
}}
// Or use presets:
transition={{ type: "spring", bounce: 0.25 }}Tween (지속 시간 기반)
transition={{
type: "tween",
duration: 0.5, // Time in seconds
ease: "easeInOut", // Easing function
}}
// Available easings:
// - "linear"
// - "easeIn", "easeOut", "easeInOut"
// - "circIn", "circOut", "circInOut"
// - "backIn", "backOut", "backInOut"
// - [0.42, 0, 0.58, 1] // Custom bezier curve애니메이션 타입 비교
자연스러운 바운스와 오버슈트 주목
Keyframes 애니메이션
// Animate through multiple values
<motion.div
animate={{
scale: [1, 1.2, 1.2, 1, 1],
rotate: [0, 0, 180, 180, 0],
borderRadius: ["0%", "0%", "50%", "50%", "0%"],
}}
transition={{
duration: 2,
times: [0, 0.2, 0.5, 0.8, 1],
repeat: Infinity,
}}
/>전환 옵션
delay
시작 전 대기 (초 단위)
repeat
반복 횟수 (루프의 경우 Infinity)
repeatType
"loop" | "reverse" | "mirror"
repeatDelay
반복 사이 일시 정지
속성별 전환
// Different transitions for different properties
<motion.div
animate={{ x: 100, opacity: 1 }}
transition={{
x: { type: "spring", stiffness: 100 },
opacity: { duration: 0.2 },
}}
/>
// The x property uses spring physics,
// while opacity uses a simple tween성능 & 접근성
성능과 포용적 디자인을 위한 애니메이션 최적화
성능 팁
Transform 속성 사용
x, y, scale, rotate는 GPU 가속됩니다. width, height, top, left 애니메이션을 피하세요.
동시 애니메이션 제한
한 번에 너무 많은 애니메이션 엘리먼트는 jank를 유발할 수 있습니다. 선택적으로 사용하세요.
will-change를 아껴 사용
Framer Motion이 자동으로 처리합니다. 수동으로 추가하지 마세요.
레이아웃 애니메이션은 비용이 많이 듭니다
layout prop을 신중하게 사용하세요. 가능하면 layout="position"을 고려하세요.
성능 측정
// Use Chrome DevTools Performance tab
1. Open DevTools → Performance
2. Record while interacting with animations
3. Look for:
- Long frames (> 16.67ms)
- Layout thrashing
- Paint/composite issues
// Target: 60 FPS (16.67ms per frame)
// Framer Motion DevTools (beta)
npm install @framer/motion-dev
// Visualize animation performance in dev mode접근성: Reduced Motion
사용자 선호도 존중
일부 사용자는 멀미를 경험하거나 전정 장애를 가지고 있습니다. 항상 prefers-reduced-motion 시스템 선호도를 존중하세요.
// Option 1: Use Framer Motion's built-in support
import { motion, ReducedMotionConfig } from "framer-motion";
<ReducedMotionConfig reducedMotion="user">
<App />
</ReducedMotionConfig>
// Option 2: Custom hook
import { useReducedMotion } from "framer-motion";
function Component() {
const shouldReduceMotion = useReducedMotion();
return (
<motion.div
animate={{
x: shouldReduceMotion ? 0 : 100,
opacity: 1, // Opacity is usually safe
}}
/>
);
}
// Option 3: CSS fallback
@media (prefers-reduced-motion: reduce) {
.animated-element {
animation: none !important;
transition: none !important;
}
}애니메이션 안티 패턴
레이아웃 속성 애니메이션
width/height는 리플로우를 유발합니다. 대신 scale transform을 사용하세요.
너무 많은 layout Props
각 layout 애니메이션은 측정이 필요합니다. 아껴 사용하세요.
모든 것을 애니메이션
목적 없는 애니메이션은 산만합니다. 각 애니메이션은 UX를 제공해야 합니다.
긴 지속 시간
UI 애니메이션을 300ms 이하로 유지하세요. 사용자는 긴 애니메이션을 느리다고 인식합니다.
좋은 애니메이션 원칙
UX 가이드라인
- 목적: 모든 애니메이션은 무언가를 전달해야 합니다
- 속도: 대부분의 UI 상호작용은 200-300ms
- 일관성: 동일한 엘리먼트는 동일한 방식으로 애니메이션되어야 합니다
- 미묘함: 애니메이션은 향상시켜야 하며, 산만하게 하면 안 됩니다
- 중단 가능성: 애니메이션은 취소 가능해야 합니다
// Recommended timing guidelines
const timings = {
// Micro-interactions (buttons, toggles)
micro: 0.1, // 100ms
// Standard transitions (modals, panels)
standard: 0.2, // 200ms
// Complex transitions (page changes)
complex: 0.3, // 300ms
// Emphasis (drawing attention)
emphasis: 0.4, // 400ms
};
// Never exceed 500ms for UI animations