> For AI agents: the complete documentation index is available at /next/llms.txt, the full documentation bundle is available at /next/llms-full.txt.

# @lynx-js/motion

`@lynx-js/motion` is a thin adaptation layer that reuses [Motion](https://motion.dev)'s source directly to bring its imperative JavaScript APIs to Lynx. All APIs run in the [main-thread script](/next/react/main-thread-script.md) environment, so animations update visual properties immediately without round-tripping through the background thread. If you know Motion's [`animate()`](https://motion.dev/docs/animate), [`motionValue()`](https://motion.dev/docs/motion-value), and [`spring`](https://motion.dev/docs/spring) on the web, you already know how to use them in Lynx. If you are new to Motion, the [Motion quick-start guide](https://motion.dev/docs/quick-start) covers the fundamentals.

:::details What is Mini and when should I use it?

The package ships two entries. The full entry has not yet reached full feature parity with Motion and has higher engine requirements. [Mini](/next/ui/motion-mini.md) is a trimmed-down build with broader compatibility, and is the entry used by lynx-ui today.

|                                                           | `@lynx-js/motion`                                    | `@lynx-js/motion/mini` ([Mini](/next/ui/motion-mini.md)) |
| --------------------------------------------------------- | ---------------------------------------------------- | -------------------------------------------------------- |
| [**Animation**](https://motion.dev/docs/animate)          | numbers, colors, unit strings, keyframe arrays       | numbers only                                             |
| [**Motion values**](https://motion.dev/docs/motion-value) | `motionValue()` (`useMotionValue` not yet supported) | `useMotionValueRef()`                                    |
| [**Spring**](https://motion.dev/docs/spring)              | `type: 'spring'`                                     | `type: 'spring'`                                         |
| [**Stagger**](https://motion.dev/docs/stagger)            | `stagger()` with selectors                           | --                                                       |
| **styleEffect**                                           | derive styles from motion values                     | --                                                       |
| **Lynx Engine**                                           | >= 3.5                                               | no minimum                                               |
| **ReactLynx**                                             | >= 0.115.2                                           | no minimum                                               |
| **Bundle size**                                           | \~275 KB                                             | \~135 KB                                                 |

:::

## Install


```sh [npm]
npm install @lynx-js/motion
```

```sh [yarn]
yarn add @lynx-js/motion
```

```sh [pnpm]
pnpm add @lynx-js/motion
```

```sh [bun]
bun add @lynx-js/motion
```

```sh [deno]
deno add npm:@lynx-js/motion
```

Import from the main package entry:

```ts
import { animate, motionValue, styleEffect } from '@lynx-js/motion';
```

## Animate an element ref

The `animate()` function accepts the same [options](https://motion.dev/docs/animate#options) as Motion on the web, including `duration`, `ease`, `delay`, `repeat`, and `type: 'spring'`. See the [Motion `animate()` reference](https://motion.dev/docs/animate) for the full option list.

The usual pattern is:

1. Create a main-thread element ref with `useMainThreadRef()`.
2. Attach it to the element with `main-thread:ref`.
3. Start [`animate()`](https://motion.dev/docs/animate) inside a main-thread function.
4. Store the animation controls in another main-thread ref so cleanup can call `stop()`.


**This is an example below: motion**

**Entry:** `src/Basic`
**Bundle:** `dist/basic.lynx.bundle` | Web: `dist/basic.web.bundle`

```tsx {20-29,41-44,58-61}
import { animate } from "@lynx-js/motion";
import { root, runOnMainThread, useEffect, useMainThreadRef } from "@lynx-js/react";
import type { MainThread } from "@lynx-js/types";

import { ThemeFrame } from "../shared/ThemeFrame";
import "./styles.css";

export default function Basic() {
  const animateMTRef = useMainThreadRef<ReturnType<typeof animate> | null>(
    null,
  );
  const boxMTRef = useMainThreadRef<MainThread.Element>(null);
  const startTimerMTRef = useMainThreadRef<ReturnType<typeof setTimeout> | null>(
    null,
  );

  function startAnimationNow() {
    "main thread";

    if (boxMTRef.current) {
      animateMTRef.current = animate(
        boxMTRef.current,
        { scale: 0.4, rotate: "45deg" },
        {
          ease: "circInOut",
          duration: 1,
          repeat: Number.POSITIVE_INFINITY,
          repeatType: "reverse",
        },
      );
    }
  }

  function startAnimation() {
    "main thread";

    if (startTimerMTRef.current) {
      clearTimeout(startTimerMTRef.current);
    }

    startTimerMTRef.current = setTimeout(() => {
      startTimerMTRef.current = null;
      startAnimationNow();
    }, 1000);
  }

  function endAnimation() {
    "main thread";

    if (startTimerMTRef.current) {
      clearTimeout(startTimerMTRef.current);
      startTimerMTRef.current = null;
    }

    animateMTRef.current?.stop();
  }

  useEffect(() => {
    void runOnMainThread(startAnimation)();
    return () => {
      void runOnMainThread(endAnimation)();
    };
  }, []);

  return (
    <ThemeFrame>
      <view className="case-container">
        <view
          className="motion-box"
          main-thread:ref={boxMTRef}
        >
        </view>
      </view>
    </ThemeFrame>
  );
}

root.render(<Basic />);

if (import.meta.webpackHot) {
  import.meta.webpackHot.accept();
}

```



## Use Springs

Set `type: 'spring'` when a value should settle with spring physics instead of following a fixed-duration easing curve. All [spring options](https://motion.dev/docs/spring) from Motion are supported, including `stiffness`, `damping`, `mass`, and `bounce`.


**This is an example below: motion**

**Entry:** `src/Spring`
**Bundle:** `dist/spring.lynx.bundle` | Web: `dist/spring.web.bundle`

```tsx {20-24,36-39}
import { animate } from "@lynx-js/motion";
import { root, runOnMainThread, useEffect, useMainThreadRef } from "@lynx-js/react";
import type { MainThread } from "@lynx-js/types";

import { ThemeFrame } from "../shared/ThemeFrame";
import "./styles.css";

export default function Spring() {
  const animateMTRef = useMainThreadRef<ReturnType<typeof animate> | null>(
    null,
  );
  const boxMTRef = useMainThreadRef<MainThread.Element>(null);
  const startTimerMTRef = useMainThreadRef<ReturnType<typeof setTimeout> | null>(
    null,
  );

  function startAnimationNow() {
    "main thread";

    if (boxMTRef.current) {
      animateMTRef.current = animate(
        boxMTRef.current,
        { rotate: 90 },
        { type: "spring", repeat: Number.POSITIVE_INFINITY, repeatDelay: 0.2 },
      );
    }
  }

  function startAnimation() {
    "main thread";

    if (startTimerMTRef.current) {
      clearTimeout(startTimerMTRef.current);
    }

    startTimerMTRef.current = setTimeout(() => {
      startTimerMTRef.current = null;
      startAnimationNow();
    }, 1000);
  }

  function endAnimation() {
    "main thread";

    if (startTimerMTRef.current) {
      clearTimeout(startTimerMTRef.current);
      startTimerMTRef.current = null;
    }

    animateMTRef.current?.stop();
  }

  useEffect(() => {
    void runOnMainThread(startAnimation)();
    return () => {
      void runOnMainThread(endAnimation)();
    };
  }, []);

  return (
    <ThemeFrame>
      <view className="case-container">
        <view
          className="motion-box"
          main-thread:ref={boxMTRef}
        >
        </view>
      </view>
    </ThemeFrame>
  );
}

root.render(<Spring />);

if (import.meta.webpackHot) {
  import.meta.webpackHot.accept();
}

```



## Use Motion Values

[`motionValue()`](https://motion.dev/docs/motion-value) stores a value, can be animated directly with `animate()`, and lets you subscribe to changes. Use it when multiple effects or event handlers need a shared animated value.


**This is an example below: motion**

**Entry:** `src/MotionValue`
**Bundle:** `dist/motion-value.lynx.bundle` | Web: `dist/motion-value.web.bundle`

```tsx {21-27,35-40}
import { motionValue } from "@lynx-js/motion";
import type { MotionValue } from "@lynx-js/motion";
import { animate } from "@lynx-js/motion";
import { root, runOnMainThread, useEffect, useMainThreadRef } from "@lynx-js/react";
import type { MainThread } from "@lynx-js/types";

import { ThemeFrame } from "../shared/ThemeFrame";
import "./styles.css";

export default function Basic() {
  const boxMTRef = useMainThreadRef<MainThread.Element>(null);
  const animateMTRef = useMainThreadRef<ReturnType<typeof animate> | null>(
    null,
  );
  const valueMTRef = useMainThreadRef<MotionValue<number>>();
  const unsubscribeMTRef = useMainThreadRef<(() => void) | null>(null);

  function bindMotionValueCallback() {
    "main thread";

    valueMTRef.current ??= motionValue(0.5);

    unsubscribeMTRef.current = valueMTRef.current.on("change", (value) => {
      boxMTRef.current?.setStyleProperties({
        transform: `scale(${value})`,
      });
    });
  }

  function startAnimation() {
    "main thread";

    bindMotionValueCallback();

    if (valueMTRef.current) {
      animateMTRef.current = animate(valueMTRef.current, [0.8, 1.4], {
        duration: 1,
        repeat: Number.POSITIVE_INFINITY,
        repeatType: "reverse",
      });
    }
  }

  function endAnimation() {
    "main thread";

    animateMTRef.current?.stop();

    if (unsubscribeMTRef.current) {
      unsubscribeMTRef.current();
      unsubscribeMTRef.current = null;
    }
  }

  useEffect(() => {
    void runOnMainThread(startAnimation)();
    return () => {
      void runOnMainThread(endAnimation)();
    };
  }, []);

  return (
    <ThemeFrame>
      <view className="case-container">
        <view
          className="motion-box"
          main-thread:ref={boxMTRef}
        >
        </view>
      </view>
    </ThemeFrame>
  );
}

root.render(<Basic />);

if (import.meta.webpackHot) {
  import.meta.webpackHot.accept();
}

```



## Build Gesture Effects

For high-frequency touch input, keep the event handlers on the main thread with `main-thread:bindtouchstart`, `main-thread:bindtouchmove`, and `main-thread:bindtouchend`. Use motion values with `styleEffect()` to derive visual state from gesture state.


**This is an example below: motion**

**Entry:** `src/iOSSlider`
**Bundle:** `dist/gesture.lynx.bundle` | Web: `dist/gesture.web.bundle`

```tsx {48-68,98-103,109-120}
import {
  animate,
  clamp,
  mapValue,
  mix,
  progress as calcProgress,
  styleEffect,
  transformValue,
  useMotionValueRef,
} from "@lynx-js/motion";
import { root, runOnMainThread, useEffect, useMainThreadRef } from "@lynx-js/react";
import type { MainThread } from "@lynx-js/types";

import SunPng from "./sun.png";

import "./styles.css";

/**
 * ==============   Configuration   ================
 */
const maxPull = 20;
const maxSquish = 0.92;
const maxStretch = 1.08;

export default function Comp() {
  /**
   * ==============   State   ================
   */
  const sliderRef = useMainThreadRef<MainThread.Element>(null);
  const progressRef = useMotionValueRef(0.5);
  const sizeRef = useMainThreadRef({ top: 0, bottom: 0 });
  const initialDragYRef = useMainThreadRef(0);
  const initialProgressYRef = useMainThreadRef(0);

  function measureSlider() {
    "main thread";
    void sliderRef.current?.invoke("boundingClientRect").then(
      (res: { top: number; bottom: number }) => {
        sizeRef.current = { top: res.top, bottom: res.bottom };
      },
    );
  }

  function initEffects() {
    "main thread";
    measureSlider();

    const y = mapValue(progressRef.current, [-1, 0, 1, 2], [
      maxPull,
      0,
      0,
      -maxPull,
    ]);
    const scaleX = mapValue(
      y,
      [-maxPull, 0, 0, maxPull],
      [maxSquish, 1, 1, maxSquish],
    );
    const scaleY = mapValue(
      y,
      [-maxPull, 0, 0, maxPull],
      [maxStretch, 1, 1, maxStretch],
    );

    styleEffect(".slider", { y, scaleX, scaleY });

    styleEffect(".indicator", {
      scaleY: transformValue(() => clamp(0, 1, progressRef.current.get())),
    });

    const invertScaleX = transformValue(() => 1 / scaleX.get());
    const invertScaleY = transformValue(() => 1 / scaleY.get());
    styleEffect(".icon-container", {
      scaleX: invertScaleX,
      scaleY: invertScaleY,
    });
  }

  useEffect(() => {
    void runOnMainThread(initEffects)();
  }, []);

  function onTouchStart(e: MainThread.TouchEvent) {
    "main thread";
    progressRef.current.stop();

    initialDragYRef.current = e.detail.y;
    initialProgressYRef.current = mix(
      sizeRef.current.bottom,
      sizeRef.current.top,
      progressRef.current.get(),
    );
  }

  function onTouchMove(e: MainThread.TouchEvent) {
    "main thread";

    const dragOffset = e.detail.y - initialDragYRef.current;
    const newProgressY = initialProgressYRef.current + dragOffset;

    progressRef.current.set(
      calcProgress(sizeRef.current.bottom, sizeRef.current.top, newProgressY),
    );
  }

  function onTouchEnd(_e: MainThread.TouchEvent) {
    "main thread";
    // Animate back to bounds if needed
    if (progressRef.current.get() < 0) {
      animate(progressRef.current, 0, {
        type: "spring",
        stiffness: 200,
        damping: 60,
      });
    } else if (progressRef.current.get() > 1) {
      animate(progressRef.current, 1, {
        type: "spring",
        stiffness: 200,
        damping: 60,
      });
    }
  }

  return (
    <view className="case-container">
      <view
        className="slider"
        main-thread:ref={sliderRef}
        main-thread:bindtouchstart={onTouchStart}
        main-thread:bindtouchmove={onTouchMove}
        main-thread:bindtouchend={onTouchEnd}
      >
        <view className="indicator"></view>
        <view className="icon-container">
          <image className="icon" src={SunPng} />
        </view>
      </view>
    </view>
  );
}

root.render(<Comp />);

if (import.meta.webpackHot) {
  import.meta.webpackHot.accept();
}

```



:::info
Motion's web-only gesture APIs such as [`scroll()`](https://motion.dev/docs/scroll), [`inView()`](https://motion.dev/docs/inview), [`hover()`](https://motion.dev/docs/hover), and [`press()`](https://motion.dev/docs/press) are not part of `@lynx-js/motion`. Use the main-thread touch events shown above instead.
:::
