Skip to main content
CodeSpeedTest
Languages
Start TypingJump into a test — pick any languageAdaptive TrainingUnlock chars as you master themPractice DrillsFocused sessions targeting weak spotsDaily ChallengesNew coding challenges every dayRace ModeCompete against others in real timeAI OpponentRace against an AI at your WPM levelTournamentsLive coding speed tournamentsArcade GamesZType, Overkill Survival, Glyphica & moreGamificationXP, coins, badges & quests
LeaderboardGlobal rankings for every languageCertificatesEarn verifiable Bronze / Silver / Gold certsActivityDaily streaks & historical analyticsProfileYour stats, badges & achievements
Browse Languages500+ languages with real code examplesBlogTips, guides & deep divesFree ToolsWPM calculator, typing speed report & moreFAQCommon questions answeredGetting StartedNew to CodeSpeedTest?AboutOur story & missionSupportGet help — Pro users get priorityContactGet in touch with the team
Pricing
  1. Home
  2. /
  3. Learn
  4. /
  5. Framer-motion

Learn Framer-motion - 10 Code Examples & CST Typing Practice Test

Framer Motion is a production-ready animation library for React, designed to create smooth, declarative animations, gestures, and transitions in web applications.

View all 10 Framer-motion code examples →
Simple Framer Motion AnimationFramer Motion Fade InFramer Motion Slide InFramer Motion BounceFramer Motion RotateFramer Motion Scale Up DownFramer Motion Hover EffectFramer Motion DragFramer Motion Stagger ChildrenFramer Motion Keyframes

Learn FRAMER-MOTION with Real Code Examples

Updated Nov 26, 2025

Explain

Framer Motion allows developers to animate React components declaratively.

It provides support for gestures such as drag, hover, tap, and scroll.

Animations can be controlled with spring physics or keyframes for natural motion.

It integrates seamlessly with React’s component model, allowing animations to respond to state changes.

Supports layout animations, shared element transitions, and exit/enter animations for complex UI interactions.

Core Features

motion.div, motion.span, motion.svg components

Variants to define reusable animation states

Keyframes and transition controls

AnimatePresence for mounting/unmounting animations

Drag and gesture controls

Basic Concepts Overview

motion - enhanced React component for animation

Variants - reusable animation states

Transition - defines timing, easing, or physics

AnimatePresence - handles mount/unmount animations

motionValue - reactive value for animation control

Project Structure

App.js - main React app

components/ - React components with motion wrappers

animations/ - reusable variants and transition configs

hooks/ - optional motionValue or gesture hooks

pages/ - pages with AnimatePresence transitions

Building Workflow

Identify components to animate

Wrap them with motion components

Define initial, animate, and exit states

Attach gesture handlers if needed

Test animations and refine timing/easing

Difficulty Use Cases

Beginner: simple fade/slide animations

Intermediate: staggered child animations

Advanced: layout and shared element transitions

Expert: interactive drag/scroll animations

Architect: complex multi-component UI choreography

Comparisons

Framer Motion vs React Spring: Framer Motion easier for declarative UI; Spring more physics-focused

Framer Motion vs GSAP: GSAP more powerful for timeline/sequenced animations, works outside React

Framer Motion vs Anime.js: Anime.js lower-level, Framer Motion integrates directly with React

Framer Motion vs CSS transitions: JS-driven animations more flexible and interactive

Framer Motion vs Lottie: Lottie is vector animation playback; Framer Motion is dynamic UI animation

Versioning Timeline

2018 - Initial release of Framer Motion

2019 - Gesture and drag support added

2020 - AnimatePresence and exit animations introduced

2022 - Layout animations and shared element transitions

2024-2025 - Performance optimizations and expanded React integration

Glossary

motion - animated React component

variant - predefined animation state

transition - controls timing and easing

AnimatePresence - animates mounting/unmounting components

motionValue - reactive value for advanced animation control

Installation Setup

Install via npm: npm install framer-motion

Import motion components: import { motion } from 'framer-motion'

Wrap components with motion tags (motion.div, motion.span)

Define animation variants or props

Use AnimatePresence for component enter/exit animations

Environment Setup

React project (CRA, Vite, Next.js)

Modern browser with CSS transform support

Optional TypeScript for type-safe motion props

React dev tools for debugging

Framer Motion visualizer for variants

Config Files

package.json - dependency management

App.js - main React app with motion components

components/ - motion-enhanced components

animations/ - reusable variants and transitions

hooks/ - optional custom motionValue or gesture hooks

Cli Commands

npm install framer-motion - install library

npm run start - start React dev server

npm run build - production build with animations

npm test - test animated components

npm run lint - ensure code quality

Internationalization

Animations are language-agnostic

Text direction changes (RTL) do not affect motion

Dynamic content can animate naturally

Variants can be reused for different locales

No internal language restrictions

Accessibility

Respect prefers-reduced-motion user setting

Ensure keyboard focusable elements remain interactive

Use ARIA roles for animated components

Avoid motion that causes disorientation

Animations should enhance, not hinder, UX

Ui Styling

CSS or styled-components for static styles

motion components handle transforms, opacity, scale

Integrates with Tailwind or other utility-first frameworks

Dynamic style changes via animate props

Supports responsive animations via media queries

State Management

React state or Redux/Zustand for dynamic animations

motionValues for reactive animation control

Variants synced with component props

AnimatePresence handles conditional components

Gestures trigger state updates for motion

Data Management

No special data persistence needed

Animation state tied to React component state

motionValues update in real-time

Shared layout animations respond to DOM changes

Complex interactions managed via props and callbacks

Architecture

Built as React components and hooks

Animation engine handles springs, keyframes, and layout transforms

Integrates with React’s virtual DOM lifecycle

Supports gesture detection and event-driven animation

Provides utility hooks for motion values and animation controls

Rendering Model

Transforms and opacity handled via DOM or CSS

Spring or keyframe-based physics engine

motionValues track dynamic changes

AnimatePresence manages component lifecycle animations

Browser GPU acceleration where applicable

Architectural Patterns

Declarative React component approach

Variants for reusable animation states

Event-driven animation updates

MotionValue reactive updates

Component hierarchy-aware animations

Real World Architectures

Interactive dashboards with animated charts

Landing pages with engaging micro-interactions

Complex forms with feedback animations

Drag-and-drop sortable UI elements

Page transitions in React single-page apps

Design Principles

Declarative API for React components

Focus on natural and smooth motion

Integrated gesture and animation control

Support dynamic UI state changes

Simple syntax for reusable animation variants

Scalability Guide

Reuse variants across components

Minimize unnecessary re-renders

Batch animations where possible

Use reduced motion for low-performance devices

Profile animations with browser performance tools

Migration Guide

Replace CSS transitions with motion components

Move JavaScript animations to declarative variants

Wrap conditional components in AnimatePresence

Use motionValues for reactive state-driven animations

Refactor gesture handlers with drag/hover/tap props

Performance Notes

Use hardware-accelerated transforms (translate3d, opacity)

Minimize re-renders while animating

Batch animations using variants

Avoid animating layout-heavy properties (width/height) frequently

Use useReducedMotion for accessibility

Security Notes

No major security concerns; runs in browser sandbox

Validate any user-provided gesture or drag inputs

Avoid exposing motionValue state to untrusted sources

Keep third-party dependencies updated

Animations should not interfere with focus management or accessibility

Monitoring Analytics

Track frame rate and animation smoothness

Monitor interactive gesture responsiveness

Profile AnimatePresence mount/unmount times

Inspect motionValues for state correctness

Log user interactions triggering animations

Code Quality

Use variants for reusable animations

Keep motion components modular

Avoid inline animation objects in render

Profile performance on nested motion components

Follow React and Framer Motion best practices

Practical Examples

Button hover and tap effects

Modal enter/exit animations

Page transitions in React Router apps

Drag-and-drop sortable lists

Animated charts and dashboards

Troubleshooting

Check if motion components are used instead of regular HTML tags

Ensure AnimatePresence wraps conditional rendering

Verify React version compatibility

Debug conflicting CSS transforms

Inspect motionValue updates in console

Testing Guide

Test animations in different browsers

Use React dev tools to inspect props

Check accessibility and reduced motion settings

Verify performance on low-end devices

Validate AnimatePresence behavior on mount/unmount

Deployment Options

Deploy standard React apps (Vite, CRA, Next.js)

SSR-compatible animations with framer-motion/next

Use code splitting to reduce bundle size

Include production minified library

Test animations in staging before production

Tools Ecosystem

Framer Motion core library

Framer prototyping tool for inspiration

React developer tools for debugging animations

Framer Motion visualizer for debugging variants

Community hooks and animation helpers

Integrations

React Router for page transitions

Styled-components or TailwindCSS for styling

Recoil, Redux, or Zustand for state-driven animations

Three.js or Canvas for hybrid UI/3D effects

Framer design files for exportable animations

Productivity Tips

Define reusable variants

Leverage AnimatePresence for conditional UI

Batch multiple animations

Use motionValues for shared state

Profile and optimize animations continuously

Challenges

Handling multiple nested motion components

Performance with frequent layout changes

Synchronizing animations with state updates

Gesture conflicts on nested elements

Accessibility and reduced motion compliance

Learning Path

Learn motion component basics

Understand variants and transitions

Add gestures and interactive animations

Use AnimatePresence for dynamic mounting

Combine with state management for complex UI

Skill Improvement Plan

Week 1: Basic motion.div and simple transitions

Week 2: Variants and reusable animations

Week 3: Gesture-based animations

Week 4: AnimatePresence and page transitions

Week 5: Advanced layout and shared element transitions

Interview Questions

Explain how Framer Motion handles declarative animations in React.

How do variants work in Framer Motion?

Describe AnimatePresence and when to use it.

How would you optimize performance for complex animations?

Explain handling gestures like drag or tap in Framer Motion.

Cheat Sheet

<motion.div initial={{opacity:0}} animate={{opacity:1}} />

const variants = { hidden:{opacity:0}, visible:{opacity:1} }

<motion.div variants={variants} initial='hidden' animate='visible' />

<AnimatePresence>{condition && <motion.div exit={{opacity:0}} />}</AnimatePresence>

const x = useMotionValue(0); <motion.div style={{ x }} drag='x' />

Books

Mastering Framer Motion for React

React Animation with Framer Motion

Interactive UI Design with Framer Motion

Advanced React Animations Handbook

Declarative Animations in React

Tutorials

Getting started with Framer Motion

Animating React components with variants

Gesture-based interactions tutorial

AnimatePresence for component transitions

Layout and shared element animation guide

Official Docs

https://www.framer.com/motion/

https://www.framer.com/docs/

Community Links

Framer Motion GitHub

Framer forum

Reactiflux Discord

Stack Overflow framer-motion tag

Reddit React/Framer discussions

Community Support

Framer Motion GitHub

Framer community forum

Reactiflux Discord

Stack Overflow: framer-motion tag

Reddit React/Framer discussions

Monetization

Premium SaaS dashboards with smooth UI

Landing pages for client projects

Interactive e-commerce product displays

Subscription-based UI components with animations

Animation libraries for internal design systems

Future Roadmap

Better SSR support and hydration

Expanded layout and shared element animations

More built-in gestures and physics behaviors

Optimized performance for large component trees

Integration with 3D and canvas-based React animations

When Not To Use

Non-React projects

High-performance game engine rendering

Heavy canvas or WebGL animations

Animations outside DOM elements (e.g., SVG libraries not supported)

Projects needing timeline-based sequences with absolute control

Final Summary

Framer Motion is a React animation library for declarative, interactive UI animations.

Supports gestures, layout animations, and component transitions.

Integrates tightly with React state and lifecycle.

Flexible for both simple and complex interactive animations.

Widely used for modern web app interfaces and micro-interactions.

Faq

Can I use Framer Motion outside React? -> No, React only

Does it support gestures? -> Yes, drag, hover, tap, scroll

Is it production-ready? -> Yes, optimized for performance

Can I animate SVG? -> Yes, motion.svg components

Does it work with SSR? -> Yes, with Next.js support

Code Sample Descriptions

1

Simple Framer Motion Animation

# framer_motion/demo/App.jsx
import React from 'react';
import { motion } from 'framer-motion';

function App() {
    return (
        <motion.div
        style={{ width: 100, height: 100, backgroundColor: 'blue' }}
        animate={{ scale: 1.5, rotate: 360 }}
        duration={2}
        />
    );
}

export default App;

A basic Framer Motion example animating a div element scaling up and rotating on render.

Let’s Try →
2

Framer Motion Fade In

# framer_motion/demo/fade_in.jsx
import React from 'react';
import { motion } from 'framer-motion';

function FadeIn() {
    return (
        <motion.div
        style={{ width: 100, height: 100, backgroundColor: 'red' }}
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        duration={1}
        />
    );
}

export default FadeIn;

Animates a div fading in on mount.

Let’s Try →
3

Framer Motion Slide In

# framer_motion/demo/slide_in.jsx
import React from 'react';
import { motion } from 'framer-motion';

function SlideIn() {
    return (
        <motion.div
        style={{ width: 100, height: 100, backgroundColor: 'green' }}
        initial={{ x: -200 }}
        animate={{ x: 0 }}
        duration={1}
        />
    );
}

export default SlideIn;

Slides a div in from the left.

Let’s Try →
4

Framer Motion Bounce

# framer_motion/demo/bounce.jsx
import React from 'react';
import { motion } from 'framer-motion';

function Bounce() {
    return (
        <motion.div
        style={{ width: 100, height: 100, backgroundColor: 'orange' }}
        animate={{ y: [0, -50, 0] }}
        transition={{ duration: 1, repeat: Infinity }}
        />
    );
}

export default Bounce;

Bounces a div up and down.

Let’s Try →
5

Framer Motion Rotate

# framer_motion/demo/rotate.jsx
import React from 'react';
import { motion } from 'framer-motion';

function Rotate() {
    return (
        <motion.div
        style={{ width: 100, height: 100, backgroundColor: 'purple' }}
        animate={{ rotate: 360 }}
        transition={{ duration: 2, repeat: Infinity }}
        />
    );
}

export default Rotate;

Rotates a div continuously.

Let’s Try →
6

Framer Motion Scale Up Down

# framer_motion/demo/scale_up_down.jsx
import React from 'react';
import { motion } from 'framer-motion';

function ScaleUpDown() {
    return (
        <motion.div
        style={{ width: 100, height: 100, backgroundColor: 'yellow' }}
        animate={{ scale: [1, 1.5, 1] }}
        transition={{ duration: 1, repeat: Infinity }}
        />
    );
}

export default ScaleUpDown;

Scales a div up and down repeatedly.

Let’s Try →
7

Framer Motion Hover Effect

# framer_motion/demo/hover_effect.jsx
import React from 'react';
import { motion } from 'framer-motion';

function HoverEffect() {
    return (
        <motion.div
        style={{ width: 100, height: 100, backgroundColor: 'pink' }}
        whileHover={{ scale: 1.2 }}
        transition={{ duration: 0.3 }}
        />
    );
}

export default HoverEffect;

Scales a div when hovered.

Let’s Try →
8

Framer Motion Drag

# framer_motion/demo/drag.jsx
import React from 'react';
import { motion } from 'framer-motion';

function Drag() {
    return (
        <motion.div
        style={{ width: 100, height: 100, backgroundColor: 'cyan' }}
        drag
        />
    );
}

export default Drag;

Makes a div draggable.

Let’s Try →
9

Framer Motion Stagger Children

# framer_motion/demo/stagger_children.jsx
import React from 'react';
import { motion } from 'framer-motion';

function StaggerChildren() {
    return (
        <motion.div
        initial="hidden"
        animate="visible"
        variants={{
        hidden: {},
        visible: { transition: { staggerChildren: 0.2 } }
        }}>
        <motion.div style={{ width: 50, height: 50, backgroundColor: 'red' }} variants={{ hidden:{opacity:0}, visible:{opacity:1} }}/>
        <motion.div style={{ width: 50, height: 50, backgroundColor: 'green' }} variants={{ hidden:{opacity:0}, visible:{opacity:1} }}/>
        <motion.div style={{ width: 50, height: 50, backgroundColor: 'blue' }} variants={{ hidden:{opacity:0}, visible:{opacity:1} }}/>
        </motion.div>
    );
}

export default StaggerChildren;

Animates multiple divs with staggered timing.

Let’s Try →
10

Framer Motion Keyframes

# framer_motion/demo/keyframes.jsx
import React from 'react';
import { motion } from 'framer-motion';

function Keyframes() {
    return (
        <motion.div
        style={{ width: 100, height: 100, backgroundColor: 'orange' }}
        animate={{ x: [0, 100, 0], rotate: [0, 180, 360] }}
        transition={{ duration: 2, repeat: Infinity }}
        />
    );
}

export default Keyframes;

Animates a div using keyframes for multiple properties.

Let’s Try →

Frequently Asked Questions about Framer-motion

What is Framer-motion?

Framer Motion is a production-ready animation library for React, designed to create smooth, declarative animations, gestures, and transitions in web applications.

What are the primary use cases for Framer-motion?

Page and component transitions. Interactive UI animations and micro-interactions. Drag-and-drop gestures. Animated modals, menus, and notifications. Shared element transitions and layout animations

What are the strengths of Framer-motion?

Deep integration with React. Simple declarative syntax. Supports complex UI animations easily. Cross-browser performance optimized. Flexible API for interactive and dynamic animations

What are the limitations of Framer-motion?

React-only library. Can increase bundle size for large apps. Complex animations may need fine-tuning for performance. Limited low-level WebGL-like graphics control. Requires understanding of React state for dynamic animations

How can I practice Framer-motion typing speed?

CodeSpeedTest offers 10+ real Framer-motion code examples for typing practice. You can measure your WPM, track accuracy, and improve your coding speed with guided exercises.

Learn Other Programming Languages

CReactPythonC++RustTypeScriptKotlinPHPJavaC#RubyMqlCqlN1qlCypherGremlinPartiqlHaskellElixirFsharpView all languages →
CodeSpeedTest

Improve your coding speed, code accuracy, and programming syntax WPM with practice sessions across 500+ programming languages.

Quick Links

HomeAboutFeaturesGetting StartedLanguages

Legal & Support

Pro ⚡ PricingContactPrivacy PolicyTerms of Service

Connect

CodeSpeedTest on GitHubCodeSpeedTest on TwitterEmail CodeSpeedTest

© 2026 CodeSpeedTest. All rights reserved.