frame
Schedule a function to run on Motion's animation loop.
Framer Motion uses an animation loop to batch reads, updates and renders once every animation frame. frame
allows access to this animation loop.
Using frame
:
- Prevents layout thrashing,
- Provides an easy keep-alive API for creating your own animation loop,
- Avoids the performance overhead of multiple
requestAnimationFrame
calls.
#Usage
#Import
// Reactimport { frame } from "framer-motion"
// Universalimport { frame } from "framer-motion/dom"
#Schedule a callback
frame
works like requestAnimationFrame
, whereby callbacks provided will execute on the next animation frame.
frame
splits the animation frame into three steps:
read
: Read values from or measure the DOM.update
: Amend values once all values have been read.render
: Apply updated values to DOM once all values have been updated.
A function can be scheduled to run at each step:
let width = 0
frame.read(() => { width = element.getBoundingClientRect().width})
frame.update(() => { width = width * 2})
frame.render(() => { element.style.width = width + "px"})
#Cancel a callback
cancelFrame
can be used to cancel a callback.
import { frame, cancelFrame } from "framer-motion"
frame.read(measureElement)cancelFrame(measureElement)
#Keep-alive
Often, you'll want to run a function every frame. You can do so by passing true
as the second argument.
let x = 0
frame.update(() => x++, true)