Motion+

HTML content

An example using Motion for React to animate HTML content by rendering a MotionValue.

React
Tutorial time
5 min
Difficulty

Tutorial

Introduction

The HTML Content example shows how to animate numerical content in React without animating React state. This is much better for performance.

The magic is in the motion component's ability to render motion values. This bypasses React's diffing algorithm, and assigns the value of the motion value to the DOM node directly.

Get started

Let's start with a basic component structure:

export default function HTMLContent() {
    return <pre style={{ fontSize: 64, color: "#61afef" }}>0</pre>
}

Let's animate!

Import from Motion

First, we'll import the necessary hooks and functions from Motion:

import { animate, motion, useMotionValue, useTransform } from "motion/react"

Creating the animation

  1. Create a motion value to track our counter:
const count = useMotionValue(0)
  1. Use useTransform to round the number as it animates:
const rounded = useTransform(() => Math.round(count.get()))
  1. Start the animation when the component mounts using Motion's animate function:
useEffect(() => {
    const controls = animate(count, 100, { duration: 5 })
    return () => controls.stop()
}, [])
  1. Display the animated value using a motion.pre component:
return <motion.pre style={text}>{rounded}</motion.pre>

Conclusion

In this tutorial, we learned how to:

  • Create an animated counter using useMotionValue
  • Transform motion values into new values with useTransform
  • Start and clean up animations with useEffect
  • Display animated numerical content in a React component

Source code

"use client"

import { animate, motion, useMotionValue, useTransform } from "motion/react"
import { useEffect } from "react"

export default function HTMLContent() {
    const count = useMotionValue(0)
    const rounded = useTransform(() => Math.round(count.get()))

    useEffect(() => {
        const controls = animate(count, 100, { duration: 5 })
        return () => controls.stop()
    }, [])

    return (
        <motion.div
            style={{
                fontFamily: "var(--font-mono)",
                fontSize: 64,
                lineHeight: 1,
                color: "var(--hue-6)",
            }}
        >
            {rounded}
        </motion.div>
    )
}

Related examples

Latest in React

Motion+

Unlock all 400+ examples

  • Source code for every Plus example.
  • Provide examples direct to your agent via Motion's MCP.
  • Lifetime access to new examples and APIs.