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. Preact-motion

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

Preact Motion is a lightweight animation library for Preact that provides physics-based, spring-driven animations similar to React-Motion. It brings declarative motion primitives such as springs, presets, transitions, and dynamic interpolation tailored for Preact’s small footprint and high performance.

View all 10 Preact-motion code examples →
Simple Fade InScale UpFade + ScaleSlide RightSlide UpRotateScale + RotateFade + Slide RightFade + Slide UpBounce Scale

Learn PREACT-MOTION with Real Code Examples

Updated Nov 26, 2025

Explain

Uses spring physics for natural movement.

Designed specifically for Preact’s lightweight component model.

Declarative motion components like Motion, StaggeredMotion, and TransitionMotion.

Automatically interpolates animated values.

Great for smooth UI animations without heavy dependencies.

Core Features

Motion - animate single style object

StaggeredMotion - sequential motion

TransitionMotion - animate mounting lists

Spring - physics engine wrapper

Presets - gentle, wobbly, stiff springs

Basic Concepts Overview

Springs: natural motion vs linear

Motion component controls interpolation

StaggeredMotion chains multiple animations

TransitionMotion handles dynamic lists

Presets for common spring behaviors

Project Structure

components/ - animated UI parts

motion/ - spring presets

styles/ - optional CSS

hooks/ - interaction handlers

App.jsx - root animations

Building Workflow

Define animated values using spring()

Wrap UI with Motion

Output styles in render callback

Animate layout or transforms

Add StaggeredMotion for sequences

Difficulty Use Cases

Beginner: fade and scale

Intermediate: accordion or toggle

Advanced: draggable element with springs

Expert: list animations with TransitionMotion

Architect: full motion library integration

Comparisons

Preact Motion vs React-Motion: nearly identical API, Preact-optimized.

Preact Motion vs Framer Motion: PM is lighter, FM has more features.

Preact Motion vs React Spring: PM simpler, smaller.

Preact Motion vs CSS: PM allows physics-based interpolation.

Preact Motion vs GSAP: GSAP for timelines, PM for UI springs.

Versioning Timeline

2015 - Inspiration from React-Motion

2018 - First Preact Motion builds appear

2020 - Full community adoption

2023 - Updates for Preact X

2025 - Stable spring-based animation solution

Glossary

Spring - physics-based interpolation

Motion - animates a single object

StaggeredMotion - sequence animations

TransitionMotion - list transitions

Preset - predefined spring configs

Installation Setup

npm install preact-motion

Import Motion, spring, or presets

Wrap component styles with Motion

Define spring physics config

Render animated styles via render function

Environment Setup

Preact + Vite environment

Basic CSS setup

Browser with requestAnimationFrame

Optional Tailwind

Node 18+ recommended

Config Files

motionPresets.js

animations.js

App.jsx (root motion)

MotionConfigs.js

routesMotion.js

Cli Commands

npm install preact-motion

npm run dev

npm run build

vite preview

npm install preact-router (optional)

Internationalization

RTL-friendly

Layout changes animate uniformly

Text updates transition smoothly

Locale-independent physics

Works with any i18n library

Accessibility

Honors prefers-reduced-motion

Avoids distracting extreme wobble

Animations are non-blocking

DOM order preserved

No impact on screen readers

Ui Styling

Animated styles returned per frame

Supports transforms, opacity, layout

Combine with CSS classes

Works with utility frameworks

Supports interpolation chaining

State Management

State drives target animation values

Springs calculate intermediate states

Signals or stores can trigger animation

Clean state changes prevent jitter

TransitionMotion tracks list state

Data Management

Keys required for list animations

State defines animation targets

Springs maintain internal velocity

Presets help unify motion behavior

Multiple motions can sync via state

Architecture

Physics simulation loop

Declarative props -> animated styles

Value interpolators per frame

Component-based animation flow

List enter/exit using TransitionMotion

Rendering Model

Runs spring physics on each frame

Interpolates numeric values

Updates Preact VDOM

Maps animation state -> style object

Remount logic for TransitionMotion

Architectural Patterns

Render-prop style output

Declarative style state

Value-driven animations

Component-wrapped motion behavior

List animation orchestration

Real World Architectures

Animated mobile UI components

Lightweight landing pages

IoT control dashboards

Micro-frontend animated panels

WASM + Preact hybrid PWAs

Design Principles

Small and fast

Declarative animations

Natural physics modeling

Preact-first design

Simple, understandable APIs

Scalability Guide

Group motions for batching

Use presets for consistency

Avoid huge animated lists

Tune physics for performance

Split heavy motion components

Migration Guide

Replace CSS transitions with springs

Wrap key elements in Motion

Move dynamic values to state

Refactor lists to TransitionMotion

Modularize spring presets

Performance Notes

Avoid animating box-shadow or filter

Use transforms for best performance

Natural springs reduce CPU spikes

Preact’s small VDOM helps with animation loops

Avoid large animated lists

Security Notes

No DOM injection or unsafe operations

Animations run purely in JS

Safe for all Preact environments

Avoid exposing debug physics data

Completely client-side

Monitoring Analytics

Track FPS on animated screens

Watch for dropped frames

Profile re-renders

Log spring behaviors during debugging

Check CPU impact

Code Quality

Use consistent spring configs

Document animation behavior

Avoid magic numbers

Normalize motion presets

Prefer transform/opacity

Practical Examples

Spring-based fade-in box

Expand/collapse card

Follow-the-mouse spring effect

Animating list additions/removals

Staggered menu item entrances

Troubleshooting

Check if spring() wrap is used correctly

Ensure numeric values for interpolation

Avoid animating non-interpolable CSS props

Check list keys in TransitionMotion

Verify the render-prop pattern

Testing Guide

Mock requestAnimationFrame

Validate final animated state

Use fake timers

Snapshot rendered style output

Disable motion during unit tests

Deployment Options

Static hosting (Vite/Netlify)

Embedded devices (WASM + Preact)

PWAs

Microfrontends

Edge-deployed sites

Tools Ecosystem

spring() physics helper

default presets: gentle, wobbly, stiff

Preact Signals for state inputs

Use with Preact Router

CSS utility frameworks alongside

Integrations

Preact Router for route transitions

Tailwind CSS for styling

Zustand/Signals for state

GSAP (optional combo)

WASM apps with Preact UI

Productivity Tips

Use presets for reusable springs

Combine with Preact Signals

Tune stiffness/damping carefully

Preview animations early

Keep motion logic centralized

Challenges

Debugging spring configs

Interpolation only works on numbers

Handling fast state changes

Animating multiple items

Understanding transition lifecycle

Learning Path

Learn Motion basics

Understand spring physics

Build toggle-based animations

Use StaggeredMotion

Master TransitionMotion for lists

Skill Improvement Plan

Week 1: springs + Motion

Week 2: gestures + interactions

Week 3: multi-element layouts

Week 4: transitioning lists

Week 5: production-level motion system

Interview Questions

What is spring physics in animation?

Difference between Motion and StaggeredMotion?

How does TransitionMotion animate lists?

Why is Preact Motion so lightweight?

How does interpolation work?

Cheat Sheet

import { Motion, spring } from 'preact-motion'

spring(100, { stiffness: 120 })

<Motion style={{ x: spring(0) }}>{style => ...}</Motion>

Use TransitionMotion for lists

Presets: presets.gentle / presets.wobbly / presets.stiff

Books

Mastering Preact

Modern Web Animations

Physics-Based UI Motion

Frontend Motion Systems

Designing Interactions with Springs

Tutorials

Preact Motion basics

Spring-driven expansion UI

StaggeredMotion menu example

List transitions with TransitionMotion

Building animations for PWA

Official Docs

https://github.com/developit/preact-motion

https://preactjs.com/guide

Community Links

Preact Discord

GitHub Discussions

Dev.to Preact tutorials

YouTube Preact motion guides

StackOverflow Preact tag

Community Support

Preact GitHub discussions

Preact Discord

Open-source contributors

Examples in community repos

StackOverflow preact-motion tag

Monetization

Lightweight UI component kits

Interactive embedded widgets

Premium templates for Preact

Animated SaaS dashboards

Motion-first landing pages

Future Roadmap

Stronger Preact Signals integration

Improved TypeScript support

More built-in presets

Better TransitionMotion ergonomics

Performance optimizations

When Not To Use

Highly choreographed sequences

Full gesture-driven apps

Heavy SVG animations

3D animations

Complex timelines

Final Summary

Preact Motion brings physics-based animations to Preact.

It provides Motion, StaggeredMotion, and TransitionMotion components.

Extremely lightweight, ideal for performance-sensitive apps.

Perfect for UI micro-interactions and smooth spring effects.

A minimal but powerful animation solution.

Faq

Does it support timelines? -> No.

Is it lightweight? -> Extremely.

Does it replace CSS transitions? -> For springs, yes.

Does it work in React? -> No, only Preact.

Does it handle enter/exit? -> Yes via TransitionMotion.

Code Sample Descriptions

1

Simple Fade In

# preact_motion/demo/App1.jsx
import { h } from 'preact'
import { Motion } from 'preact-motion'

export default function App() {
    return (
        <Motion defaultStyle={{ opacity: 0 }} style={{ opacity: 1 }}>
        {style => (
        <div style={{ width: 100, height: 100, background: 'red', opacity: style.opacity }} />
        )}
        </Motion>
    )
}

Fades a div in on mount

Let’s Try →
2

Scale Up

# preact_motion/demo/App2.jsx
import { h } from 'preact'
import { Motion } from 'preact-motion'

export default function App() {
    return (
        <Motion defaultStyle={{ scale: 0.5 }} style={{ scale: 1 }}>
        {style => (
        <div style={{ width: 100, height: 100, background: 'green', transform: `scale(${style.scale})` }} />
        )}
        </Motion>
    )
}

Scales up a div from 0.5 to 1

Let’s Try →
3

Fade + Scale

# preact_motion/demo/App3.jsx
import { h } from 'preact'
import { Motion } from 'preact-motion'

export default function App() {
    return (
        <Motion defaultStyle={{ opacity: 0, scale: 0.5 }} style={{ opacity: 1, scale: 1 }}>
        {style => (
        <div style={{ width: 120, height: 120, background: 'blue', opacity: style.opacity, transform: `scale(${style.scale})` }} />
        )}
        </Motion>
    )
}

Fades in and scales a div

Let’s Try →
4

Slide Right

# preact_motion/demo/App4.jsx
import { h } from 'preact'
import { Motion } from 'preact-motion'

export default function App() {
    return (
        <Motion defaultStyle={{ x: -100 }} style={{ x: 0 }}>
        {style => (
        <div style={{ width: 100, height: 100, background: 'orange', transform: `translateX(${style.x}px)` }} />
        )}
        </Motion>
    )
}

Slides a div from left to right

Let’s Try →
5

Slide Up

# preact_motion/demo/App5.jsx
import { h } from 'preact'
import { Motion } from 'preact-motion'

export default function App() {
    return (
        <Motion defaultStyle={{ y: 100 }} style={{ y: 0 }}>
        {style => (
        <div style={{ width: 100, height: 100, background: 'purple', transform: `translateY(${style.y}px)` }} />
        )}
        </Motion>
    )
}

Slides a div up from below

Let’s Try →
6

Rotate

# preact_motion/demo/App6.jsx
import { h } from 'preact'
import { Motion } from 'preact-motion'

export default function App() {
    return (
        <Motion defaultStyle={{ rotate: 0 }} style={{ rotate: 360 }}>
        {style => (
        <div style={{ width: 100, height: 100, background: 'cyan', transform: `rotate(${style.rotate}deg)` }} />
        )}
        </Motion>
    )
}

Rotates a div from 0 to 360 degrees

Let’s Try →
7

Scale + Rotate

# preact_motion/demo/App7.jsx
import { h } from 'preact'
import { Motion } from 'preact-motion'

export default function App() {
    return (
        <Motion defaultStyle={{ scale: 0.5, rotate: 0 }} style={{ scale: 1, rotate: 360 }}>
        {style => (
        <div style={{ width: 120, height: 120, background: 'magenta', transform: `scale(${style.scale}) rotate(${style.rotate}deg)` }} />
        )}
        </Motion>
    )
}

Scales and rotates a div

Let’s Try →
8

Fade + Slide Right

# preact_motion/demo/App8.jsx
import { h } from 'preact'
import { Motion } from 'preact-motion'

export default function App() {
    return (
        <Motion defaultStyle={{ opacity: 0, x: -100 }} style={{ opacity: 1, x: 0 }}>
        {style => (
        <div style={{ width: 100, height: 100, background: 'lime', opacity: style.opacity, transform: `translateX(${style.x}px)` }} />
        )}
        </Motion>
    )
}

Fades in while sliding right

Let’s Try →
9

Fade + Slide Up

# preact_motion/demo/App9.jsx
import { h } from 'preact'
import { Motion } from 'preact-motion'

export default function App() {
    return (
        <Motion defaultStyle={{ opacity: 0, y: 50 }} style={{ opacity: 1, y: 0 }}>
        {style => (
        <div style={{ width: 100, height: 100, background: 'yellow', opacity: style.opacity, transform: `translateY(${style.y}px)` }} />
        )}
        </Motion>
    )
}

Fades in while sliding up

Let’s Try →
10

Bounce Scale

# preact_motion/demo/App10.jsx
import { h } from 'preact'
import { Motion, spring } from 'preact-motion'

export default function App() {
    return (
        <Motion defaultStyle={{ scale: 0.5 }} style={{ scale: spring(1, { stiffness: 200, damping: 10 }) }}>
        {style => (
        <div style={{ width: 100, height: 100, background: 'orange', transform: `scale(${style.scale})` }} />
        )}
        </Motion>
    )
}

Scales a div with a spring bounce effect

Let’s Try →

Frequently Asked Questions about Preact-motion

What is Preact-motion?

Preact Motion is a lightweight animation library for Preact that provides physics-based, spring-driven animations similar to React-Motion. It brings declarative motion primitives such as springs, presets, transitions, and dynamic interpolation tailored for Preact’s small footprint and high performance.

What are the primary use cases for Preact-motion?

Smooth, spring-based UI animations. Element transitions without CSS keyframes. Animated toggles and switches. Layout-based motion between states. Declarative dynamic value interpolation

What are the strengths of Preact-motion?

Very lightweight compared to Framer Motion or React Spring. Natural spring physics. Perfect for micro-interactions. Minimal API surface - easy to learn. Optimized for Preact performance

What are the limitations of Preact-motion?

Not a full animation engine (no timeline or gestures). Less feature-rich than React Spring or Framer Motion. Limited third-party ecosystem. Requires Preact - not directly usable in React. Cannot handle complex animation choreography

How can I practice Preact-motion typing speed?

CodeSpeedTest offers 10+ real Preact-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.