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])