Motion
Back to framer.com
DocumentationMotion values
useMotionValueEvent
Motion
Back to framer.com
Design and publish your first free site today.
Getting started
  • Introduction
  • Examples
Animation
  • Overview
  • Layout
  • Gestures
  • Scroll
  • Transition
Components
  • motion
  • AnimatePresence
  • LayoutGroup
  • LazyMotion
  • MotionConfig
  • Reorder
Motion values
  • Overview
  • useMotionValueEvent
  • useMotionTemplate
  • useScroll
  • useSpring
  • useTime
  • useTransform
  • useVelocity
  • useWillChange
Utilities
  • animate
  • transform
  • useAnimationControls
  • useAnimationFrame
  • useDragControls
  • useInView
  • useReducedMotion
3D
  • Introduction
  • LayoutCamera
  • LayoutOrthographicCamera
  • MotionCanvas
Guides
  • Accessibility
  • Reduce bundle size
  • Upgrade guides
Community
  • GitHub
  • Discord

useMotionValueEvent

Subscribe to motion value events from a React component.

useMotionValueEvent manages MotionValue event handlers throughout the lifecycle of a React component.

function Component() {
const x = useMotionValue(0)
useMotionValueEvent(x, "animationStart", () => {
console.log("animation started on x")
})
useMotionValueEvent(x, "change", (latest) => {
console.log("x changed to", latest)
})
return <motion.div style={{ x }} />
}

When the component is unmounted, the event handler will be safely unsubscribed automatically.

#Usage

Import from Framer Motion.

import { useMotionValueEvent } from "framer-motion"

To add an event listener to a MotionValue, provide the value, event name, and callback.

useMotionValueEvent(value, "change", (latest) => {
console.log(latest)
})

Available events are:

  • change
  • animationStart
  • animationComplete
  • animationCancel

"change" events are provided the latest value of the MotionValue.

useMotionValueEvent is a helper method for MotionValue.on. So it is still possible to set up events yourself in a useEffect, but remember to pass the on unsubscribe function to useEffect's return function to ensure it is correctly cleaned up.

useEffect(() => {
const doSomething = () => {}
const unsubX = x.on("change", doSomething)
const unsubY = y.on("change", doSomething)
return () => {
unsubX()
unsubY()
}
}, [x, y])
PreviousMotion values overviewNextuseMotionTemplate
On this page
  • Usage

Copyright © 2022 Framer B.V.

  • Security
  • Terms of Service
  • Privacy Statement