Skip to main content
withAnimation(body: () => void): Component;
withAnimation(animation: AnimationComponent, body: () => void): Component;
animation
AnimationComponent
An animation created with Spring(), InterpolatingSpring(), EaseIn(), EaseInOut(), EaseOut(), Linear(), Bouncy(), or Snappy(). If omitted, a default spring animation is used.
body
() => void
required
A function containing state mutations. All UI changes resulting from these mutations will be animated.

Returns

A Component that executes the body function within the animation context.

Usage

Default animation

const body = () => {
    const [count, setCount] = useState(0)

    return VStack([
        Text(String(count)).font("largeTitle"),
        Button("Animate +1", () => {
            withAnimation(() => setCount(count + 1))
        })
    ])
}

With a spring animation

const body = () => {
    const [isExpanded, setIsExpanded] = useState(false)

    return VStack([
        Button(isExpanded ? "Collapse" : "Expand", () => {
            withAnimation(Spring({ response: 0.5 }), () => {
                setIsExpanded(!isExpanded)
            })
        }),
        Rectangle()
            .fill(Color("blue"))
            .frame({ height: isExpanded ? 200 : 50 })
    ])
}

With an easing curve

const body = () => {
    const [offset, setOffset] = useState(0)

    return VStack([
        Rectangle()
            .fill(Color("blue"))
            .frame({ width: 50, height: 50 })
            .offset({ x: offset, y: 0 }),
        Button("Move Right", () => {
            withAnimation(EaseInOut({ duration: 0.5 }), () => {
                setOffset(offset + 100)
            })
        })
    ])
}

Notes

  • Multiple state changes within the same withAnimation block are batched into a single animated transition.
  • The animation context applies to all UI changes resulting from the state mutations, not just the direct parent view.
  • If no animation is specified, a default spring animation is used.
  • For details on available animation constructors and their options, see animations.

See Also

  • animations — all animation constructors and chainable modifiers
  • useState — component-local state