Skip to main content
Version: 5.x

withTiming

The withTiming modifier animates a value linearly or with a specified easing function to a given target over a fixed duration. It's ideal for simple, predictable transitions like fades or scales, where precise control over the animation's timing is crucial.

Syntax

withTiming(toValue, options?) => Descriptor

Parameters

  • toValue: The target value to reach. This can be a number, string, object, or array.
  • Options (optional): An object containing timing-specific settings.
OptionsDescrptionsTypeDefault
durationHow long the animation lasts (in milliseconds).number300
easingThe easing function controls the animation's acceleration and deceleration.functionTODO:
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 withTiming

This example demonstrates how to animate multiple values using useValue with timing-based animation via withTiming.

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

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

  return (
    <>
      <button
        onClick={() =>
          setObj(
            withTiming(
              { x: 0, y: 0, width: 300, height: 100 },
              {
                duration: 400,
                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 properties (x, y, width, height).
  • Animates to new values over a fixed duration (400ms) using withTiming.
  • Includes onStart and onComplete callbacks for monitoring the animation lifecycle.
  • Uses the <animate.div> component to automatically bind animated values to styles.

How it Works:

  1. The initial state has:
    • Position (0, 0)
    • Width 100, Height 100
  2. Clicking Start:
    • Animates width from 100 to 300 over 400 milliseconds.
    • Other values remain the same (x, y stay at 0, height stays at 100).
    • Logs "START" at the beginning and "Animation complete" after finishing.
  3. Clicking Reset instantly snaps it back to the initial state.