Skip to main content
Version: 5.x

withDecay

The withDecay modifier animates a value by simulating momentum with friction. You typically provide an initial velocity, and the value will coast and gradually slow to a stop. This is particularly useful for implementing flick or throw gestures, or any scenario where you want a natural slowdown effect, similar to a thrown ball gradually losing speed.

Syntax

withDecay(velocity, options?) => Descriptor

Parameters

  • velocity: The initial velocity of the animation, measured in units per millisecond.
    • Default: 0.997 per frame
  • Options (optional):
OptionsDescrptionsTypeDefault
onStartA callback function invoked when the animation begins.function()-
onChangeA callback function invoked on every frame of the animation, providing the current value.function()-
onCompleteA callback function invoked when the animation finishes.function()-

Example: Animate with withDecay (Decay-Based Animation)

This example showcases how to use decay-based animation with withDecay utility, simulating inertia-like.

import React from 'react';
import { useValue, animate, withDecay } from 'react-ui-animate';

export default function BasicExample() {
  const [obj, setObj] = useValue({ x: 0, y: 0, width: 100, height: 100 });

  return (
    <>
      <button
        onClick={() =>
          setObj(
            withDecay(0.3, {
              onStart: () => console.log('START'),
              onComplete: () => console.log('Animation complete'),
            })
          )
        }
      >
        Start
      </button>
      <button onClick={() => setObj({ x: 0, y: 0, width: 100, height: 100 })}>
        Reset
      </button>

      <animate.div
        style={{
          width: obj.width,
          height: 100,
          backgroundColor: 'teal',
          left: 0,
          top: 0,
          translateX: obj.x,
          translateY: obj.y,
          borderRadius: 4,
        }}
      />
    </>
  );
}

Key Highlights:

  • Uses useValue to handle multiple animated values (x, y, width, height).
  • Animates using decay, which gradually reduces the velocity over time—no fixed destination.
  • Animates all numeric properties using decay.
  • Includes onStart and onComplete callbacks to observe animation progress.
  • Renders the animated object via <animate.div> with styles directly tied to the values.