Command Palette

Search for a command to run...

331K21st.dev views
Blog

The Physics of Feel — Tuning Spring Animations in React and Motion

How I tune stiffness, damping, mass, visualDuration, and reduced-motion fallbacks across real motion/react components without fighting interruptibility or React renders.

Most UI animations look fine in a screen recording and feel slightly off the moment you click them twice in a row. A button label gets stuck mid-fade, a drawer snaps backward before sliding forward, or a slider handle lags a frame behind your thumb.

Across the component registry in this repository, I use motion (^13.4.0 in package.json), imported from "motion/react" (the package formerly known as Framer Motion). While building interactive controls like a morphing search bar, an elastic slider, a 3D bookshelf, and a card wallet, I kept running into the same three tuning problems: preserving velocity when a user interrupts an animation, keeping frame updates out of React renders, and writing reduced-motion fallbacks that still communicate state.

Before reaching for a spring at all, DESIGN.md sets a baseline for this site: motion explains change (state, feedback, orientation, or discovery) instead of decorating a static surface, and transform, opacity, color, and shadow take priority over layout-affecting changes. A color hover or border shift does not need spring physics. A 150 to 250ms CSS transition handles that with less code. Springs earn their complexity when an element moves through space and a pointer or state change can catch it mid-flight.

Why springs instead of easing curves

A cubic-bezier curve is a function of time. Once it starts, it expects to run from t = 0 to t = duration without interruption. If a user clicks a submit button while it is halfway through swapping its label, a time-based curve has no memory of how fast the element was already moving. It either jumps to a new curve from zero velocity or cancels abruptly.

A spring is a simulation over position and velocity. When the target changes mid-flight, the spring keeps its current position and velocity and redirects the force toward the new target.

cubic-bezier interrupted mid-flight:
  pos:  0 ------> 0.6 [status changes] 0.6 -> (velocity resets to 0) ---> 1.0
 
spring interrupted mid-flight:
  pos:  0 ------> 0.6 [status changes] 0.6 ~> (keeps momentum, redirects) -> 1.0

You can see this trade-off directly in src/registry/components/status-button/status-button.tsx:

// A spring keeps its velocity when the status changes mid-swap; a cubic-bezier
// would restart from zero.
const swapTransition: Transition = {
  type: "spring",
  duration: 0.3,
  bounce: 0,
}
 
// Bounce only on the entrance, and only on movement: opacity and blur would
// overshoot.
const successVariants: Variants = {
  ...swapVariants,
  animate: {
    ...swapVariants.animate,
    transition: {
      type: "spring",
      duration: 0.45,
      bounce: 0.35,
      opacity: swapTransition,
      filter: swapTransition,
    },
  },
}

That second comment came from breaking it first. When I applied bounce: 0.35 to the whole variant object, y got a crisp overshoot into place, while opacity and filter: blur(...) tried to overshoot past 1 and 0px. Isolating opacity and filter onto swapTransition (bounce: 0) keeps the confirmation pop physical without flashing alpha or inverting blur.

Two ways to parameterize a spring in Motion

In "motion/react", you can configure a spring with raw physics (stiffness, damping, mass) or perceptual timing (visualDuration or duration paired with bounce). I use both across the registry depending on whether I am matching a visual beat or dialing in physical weight.

Perceptual parameters are faster to tune when multiple parts of a component need to land together. In src/registry/components/wallet/wallet.tsx, cards peek, pull up, and settle back into a pocket using two constants:

const PULL_SPRING: Transition = {
  type: "spring",
  visualDuration: 0.4,
  bounce: 0.25,
}
 
const SETTLE_SPRING: Transition = {
  type: "spring",
  visualDuration: 0.25,
  bounce: 0,
}
 
const REDUCED_TRANSITION: Transition = { duration: 0 }

Using visualDuration and bounce makes the relationship between pulling a card (0.4s with a 0.25 bounce) and letting it settle (0.25s critically damped) readable at a glance. Changing how lively the pull feels is one number instead of re-balancing stiffness against damping.

When weight and snap matter more than fixed visual duration, raw physics gives finer control:

  • In src/registry/components/aurora-search-bar/aurora-search-bar.tsx, MORPH_SPRING drives the pill width between 48px and its expanded width with stiffness: 320, damping: 32, mass: 0.88. Inside that same component, smaller controls get stiffer springs so they settle before the container finishes moving: stiffness: 420, damping: 26 on the search icon hover and tap, and stiffness: 460, damping: 28 on the clear button inside AnimatePresence.
  • In src/registry/components/avatar-gender-toggle/avatar-gender-toggle.tsx, the character face travels vertically between y: 0 and y: 114 while SVG paths morph between hairstyles and glasses frames using stiffness: 270, damping: 28, mass: 0.92. Slightly lower stiffness and higher mass give the larger SVG thumb a heavier settle than a small icon button.

Tuning these numbers mostly means adjusting one axis at a time. Raise stiffness for a snappier start, lower mass so small controls do not feel sluggish, and adjust damping last to control whether the motion settles cleanly or rings once before stopping.

Keeping frame updates out of React renders

Animating a spring inside React state (useState) forces a component re-render on every tick. For pointer-driven interactions or multi-element transforms, that quickly turns into wasted reconciliation work. "motion/react" avoids this with MotionValue and useSpring, which update DOM nodes or SVG attributes outside React's render cycle.

In src/registry/components/spotlight-logo/spotlight-logo.tsx, a radial gradient follows the cursor across an SVG outline. Instead of storing coordinates in state, the pointer coordinates flow through a passive pipeline:

mousemove (clientX / innerWidth)
   |
   v
mouseX (useMotionValue, 0.5 initial)
   |
   v
useTransform(mouseX, [0, 1], [0, 556])
   |
   v
cx = useSpring(..., { stiffness: 300, damping: 30, mass: 0.1 })
   |
   v
<motion.radialGradient cx={cx} cy={cy} />

Setting mass: 0.1 keeps the gradient close to the pointer while still smoothing jagged mouse samples. The whileTap="pressed" SVG path morph on the same logo uses a heavier spring (stiffness: 200, damping: 18, mass: 0.5) so pressing the mark feels distinct from hovering across it.

Two other components in the registry push MotionValue updates imperatively because declarative props were not the right fit:

In src/registry/components/bookshelf/bookshelf.tsx, each book pivots open from 0 to 90 degrees (OPEN_ANGLE) while pushing neighboring books aside by its projected width (getItemWidth). Writing that width into a CSS custom property on every frame would trigger style recalculation across every child element inside the book, and storing angle in React state would re-render the subtree on every frame. So BookshelfItem subscribes to angle.on("change", apply) and writes directly to the wrapper's inline style.width:

const SPRING = { stiffness: 260, damping: 32 }
// Written straight to the element: a spring frame must not re-render React,
// and an animated CSS variable would restyle every descendant per frame
useEffect(() => {
  const apply = (deg: number) => {
    if (!itemRef.current) return
    const width = getItemWidth(deg, spineWidth, coverWidth)
    itemRef.current.style.width = `${width}px`
  }
  apply(angle.get())
  return angle.on("change", apply)
}, [angle, coverWidth, spineWidth])

In src/registry/components/elastic-slider/elastic-slider.tsx, the track fill follows direct pointer drags immediately via fillPercent.jump(...), then switches to an imperative animate(...) spring when the user clicks the track or nudges the value with arrow keys:

// Animate fill to a target percent, or jump instantly when the user prefers
// reduced motion. Position still updates — only the spring is skipped.
const animateFillTo = useCallback(
  (targetPercent: number) => {
    animRef.current?.stop()
 
    if (shouldReduceMotion) {
      fillPercent.jump(targetPercent)
      animRef.current = null
      return
    }
 
    animRef.current = animate(fillPercent, targetPercent, {
      type: "spring",
      stiffness: 300,
      damping: 25,
      mass: 0.8,
      onComplete: () => {
        animRef.current = null
      },
    })
  },
  [fillPercent, shouldReduceMotion]
)

Calling animRef.current?.stop() before starting a new spring, and again inside handlePointerMove, prevents an in-flight keyboard or click spring from fighting a live pointer drag. When the user drags past the left or right bounds of the slider and lets go, elastic-slider.tsx releases rubberStretch back to 0 with { type: "spring", visualDuration: 0.35, bounce: 0.15 }, while the handle itself squashes and stretches via scaleX (visualDuration: 0.25, bounce: 0.15) and scaleY (visualDuration: 0.2, bounce: 0.1).

Designing reduced-motion fallbacks into every spring

DESIGN.md makes reduced motion mandatory: cursor-following, auto-playing, or rotating animations must stop or become static under prefers-reduced-motion, and essential information must never live behind an animation. Deleting animations altogether often breaks state visibility, so across the newer components I ended up using three distinct fallback patterns via useReducedMotion().

The first pattern is switching to zero-duration or opacity-only transitions. In status-button.tsx, reduced motion swaps swapVariants (which shifts y by 8px and animates a 4px blur) for reducedMotionVariants (opacity only) with { duration: 0 }. aurora-search-bar.tsx, avatar-gender-toggle.tsx, and wallet.tsx similarly pass { duration: 0 } (or REDUCED_TRANSITION) when reduced motion is active, so state changes still happen immediately without physical travel.

The second pattern is jumping a MotionValue straight to its target and keeping a brief opacity cue when spatial continuity would otherwise disappear. In bookshelf.tsx, if (reduceMotion || instant) angle.jump(target) snaps the book open without rotating across 90 degrees, and a helper (useReducedMotionFade) runs a 150ms Web Animations API opacity: [0, 1] fade on bookRef.current. In elastic-slider.tsx, animateFillTo calls fillPercent.jump(targetPercent) and skips both the overdrag rubberStretch accumulation and its release spring.

The third pattern is gating listeners and idle loops before they even schedule frames. In spotlight-logo.tsx, the mousemove listener is skipped whenever shouldReduceMotion is true, when useInView(ref, { margin: "80px" }) is false, or when window.matchMedia("(hover: none)").matches detects a touch-primary device. In avatar-gender-toggle.tsx, idle micro-animations (lens glint and eye blink) check const shouldAnimateIdle = idleAnimations && !prefersReducedMotion. In aurora-search-bar.tsx, AuroraEdgeGlow drops its 3.4-second pulsing loop for a static opacity state when reducedMotion is enabled.

Trade-offs, layout costs, and gaps still in the repo

Springs are easy to over-apply, and auditing this codebase surfaced both design trade-offs and places where my own implementation is still incomplete.

First, two components in the registry deliberately animate layout width: bookshelf.tsx updates itemRef.current.style.width as a book turns so adjacent books shift out of the way, and aurora-search-bar.tsx animates width on its outer pill with will-change-[width]. That breaks the general preference in DESIGN.md for pure transform and opacity animations. In both cases I accepted the layout cost because neighboring siblings or inline layout needed to reflow cleanly, and kept the animated subtrees small to limit style recalculation. For simple hover highlights, border colors, or card backgrounds elsewhere on the site, a 150 to 250ms CSS transition remains simpler and cheaper.

Second, separating channels on a transition object is easy to forget until a component ships. Any time you put bounce > 0 on a transition that also animates opacity or filter, Motion applies that spring curve to every property unless you override opacity and filter with a zero-bounce transition, as in status-button.tsx.

Third, reduced-motion coverage across the registry is not 100% yet. While checking the components for this post, I found three older or smaller components that still animate springs without calling useReducedMotion:

  • src/registry/components/slide-to-unlock/slide-to-unlock.tsx runs animate(x, 0, { type: "spring", bounce: 0, duration: 0.25 }) on drag release with no reduced-motion check.
  • src/registry/components/icon-swap/icon-swap.tsx animates scale: 0.25 and filter: "blur(4px)" on a duration: 0.3, bounce: 0 spring unconditionally.
  • src/registry/components/theme-switcher/theme-switcher.tsx animates its layoutId="theme-option" indicator with { type: "spring", bounce: 0.3, duration: 0.6 } and does not read useReducedMotion.

If you are building a component library with "motion/react", treating reduced-motion support as part of the initial state model, right next to stiffness, damping, and MotionValue wiring, saves you from hunting down those gaps component by component later.

Command Palette

Search for a command to run...