UI & Styling: Motion (Framer Motion)
Framer Motion Animations: Add fluid, physics-based micro-interactions and layout transitions.
Traditional web animations rely on static CSS transitions and @keyframes. While effective for simple hover states, CSS-driven approaches introduce severe architectural friction in modern React:
- **No Dynamic Interruptibility:** If an element is animating toward x: 200px and a user gesture redirects it mid-flight, CSS snaps abruptly or awkwardly resets its easing curve.
- **Layout Shifts Trigger Jank:** Animating geometric dimensions (width, height, top, left) forces browser reflow and layout re-calculations on every frame, generating CPU spikes and dropped frames.
- **Component Unmount Blindspots:** React unmounts components instantly when conditional state flips (\{isOpen && <Modal/>\}). CSS provides no native mechanism to delay React’s DOM removal long enough to execute an exit animation without complex manual state wrappers.
- Motion (formerly Framer Motion) resolves these limitations by pairing real-time spring physics simulations with FLIP-based layout transformations and declarative lifecycle management via <AnimatePresence>.
## 1. Core Mechanics: Spring Physics vs. Duration Curves
CSS animations rely on fixed duration curves (transition: all 0.3s cubic-bezier(...)). This forces movement into an arbitrary time bucket regardless of the distance traveled or the velocity of the trigger.
Motion defaults to continuous spring physics based on classic kinematics:
Force=-kx-cv
- **Stiffness (k):** Dictates the snap and responsiveness. Higher values produce rapid, high-velocity movement.
- **Damping (c):** The frictional resistance. Low damping produces natural oscillation and bounce; high damping smoothly halts the element without overshoot.
- **Mass (m):** The virtual weight of the element. Higher mass increases inertia, causing slower acceleration and deceleration phases.
CSS Duration Easing:
```text
Start ────────────── Fixed 300ms Duration ──────────────> End (Linear / Cubic)
(Interruption causes sudden snap or restarts curve from origin)
```
Motion Spring Physics:
- Start ~~~~~/\/\/\/\~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~> Target
- (Fully interruptible: Preserves momentum and current velocity across state changes)
```ts
import * as motion from 'motion/react-client';
export function PhysicsToggle() {
return (
Interactive Feedback
);
}
```
## 2. Declarative Variants & Orchestration
Hardcoding animation values inline creates maintainability issues when building nested component trees (e.g., a slide-out drawer whose menu items must stagger into view sequentially).
Variants isolate animation dictionaries from the JSX tree, allowing parent components to orchestrate children declaratively without manual delay calculations.
```ts
'use client';
import * as motion from 'motion/react-client';
// 1. Parent container variants controlling orchestration
const containerVariants = {
hidden: { opacity: 0, scale: 0.95 },
visible: {
opacity: 1,
scale: 1,
transition: {
when: 'beforeChildren', // Animate parent surface first
staggerChildren: 0.08, // Stagger child elements by 80ms intervals
delayChildren: 0.1,
},
},
exit: {
opacity: 0,
scale: 0.95,
transition: { staggerChildren: 0.05, staggerDirection: -1 },
},
};
// 2. Child item variants
const itemVariants = {
hidden: { opacity: 0, y: 15 },
visible: {
opacity: 1,
y: 0,
transition: { type: 'spring', stiffness: 300, damping: 24 }
},
exit: { opacity: 0, y: -10 },
};
export function StaggeredDropdown({ items }: { items: string[] }) {
return (
{items.map((item) => (
{item}
))}
);
}
```
## 3. Exit Animations: <AnimatePresence>
In standard React, toggling \{isOpen: false\} tears down the DOM node on the subsequent render pass.
<AnimatePresence> intercepts component unmount cycles. It retains the unmounting Fiber node in memory, plays the designated exit animation sequence, and only unlinks the underlying DOM node once the animation completes.
```ts
'use client';
import { useState } from 'react';
import * as motion from 'motion/react-client';
import { AnimatePresence } from 'motion/react';
export function NotificationBanner() {
const [isVisible, setIsVisible] = useState(true);
return (
);
}
```
### 4.2 Shared Element Transitions (layoutId)
Shared element transitions morph an element seamlessly between distinct DOM nodes.
By tagging two different components with matching layoutId props, Motion tracks both nodes across render cycles and generates a continuous physical bridge between them (such as an active pill indicator sliding between navigation items):
```ts
'use client';
import { useState } from 'react';
import * as motion from 'motion/react-client';
const tabs = ['Overview', 'Telemetry', 'Deployments', 'Security'];
export function AnimatedTabs() {
const [activeTab, setActiveTab] = useState(tabs[0]);
return (
);
}
```
## 5. Bundle Optimization & React Server Components
In modern Next.js and full-stack React setups, animation runtimes can inflate client bundles if imported indiscriminately.
### 5.1 The Modern Import Standard
The library is distributed under the motion package. In React Server Component environments, use the optimized client-bound entry point:
```ts
// Preserves RSC boundaries without manual client boilerplate:
import * as motion from 'motion/react-client';
```
### 5.2 Tree-Shaking with LazyMotion
In large-scale applications, the full Motion bundle adds approximately 25–30 kB (gzipped) to the initial bundle.
Using <LazyMotion> with domAnimation removes unnecessary gesture and complex SVG capabilities from the critical path, deferring them until after initial page hydration:
```ts
// src/app/providers.tsx
'use client';
import { LazyMotion, domAnimation } from 'motion/react';
export function AnimationProvider({ children }: { children: React.ReactNode }) {
// Bundles strictly core animation and layout logic (~15 kB savings)
return (
{children}
);
}
```
Components consume the lightweight <m> proxy instead of <motion>:
```ts
import { m } from 'motion/react';
export function LightweightBadge() {
return Active ;
}
```
## 6. Accessibility Guardrails: useReducedMotion
Respecting system-level accessibility settings is mandatory for enterprise software. Users with vestibular conditions often configure their operating systems to minimize non-essential motion.
Motion exposes the useReducedMotion hook to gracefully collapse or disable transitions:
```ts
'use client';
import * as motion from 'motion/react-client';
import { useReducedMotion } from 'motion/react';
export function AccessibleCard() {
const shouldReduceMotion = useReducedMotion();
return (
Content respects system-level prefers-reduced-motion preferences
);
}
```
{/* AnimatePresence must directly wrap conditional elements */}
{isVisible && (
System update completed successfully.
)}
);
}
```
Core AnimatePresence Modes:
- mode="sync" (Default): Entering and exiting elements animate concurrently.
- mode="wait": The exiting element completes its full exit transition before the entering element mounts (ideal for page routing and tabs).
- mode="popLayout": Removes exiting nodes from document flow using position: absolute, preventing surrounding elements from collapsing abruptly during list mutations.
## 4. Automatic Layout Transitions: The FLIP Technique
Animating layout dimensions (sorting lists, expanding accordion panels, resizing dialogs) with CSS triggers layout reflow and composite layer repainting on every single tick, degrading frame rates.
Motion abstracts this by applying the FLIP (First, Last, Invert, Play) technique when the layout prop is present:
- **First:** Measures the initial bounding client rect (getBoundingClientRect()).
- **Last:** Applies the layout state change instantly; records the new dimensions.
- **Invert:** Computes the delta and applies hardware-accelerated CSS transform properties (scale, translate) to invert the element back to its initial visual coordinates.
- **Play:** Animates the inverse transform down to zero entirely on the GPU.
### 4.1 Smooth Reordering with Zero Jank
Adding layout turns complex list mutations into 60fps GPU-accelerated transforms:
```ts
'use client';
import { useState } from 'react';
import * as motion from 'motion/react-client';
export function SortableList() {
const [items, setItems] = useState(['Kubernetes', 'Docker', 'Terraform', 'Vault']);
const shuffle = () => setItems([...items].sort(() => Math.random() - 0.5));
return (
-
{items.map((item) => (
// layout enables automated FLIP transitions on array reordering
