Skip to content

Instantly share code, notes, and snippets.

@steveruizok
Created September 26, 2019 13:25
Show Gist options
  • Save steveruizok/87464a55de1687ca8d09a73abda33ac6 to your computer and use it in GitHub Desktop.
Save steveruizok/87464a55de1687ca8d09a73abda33ac6 to your computer and use it in GitHub Desktop.
Call a function whenever a motion value changes.
import * as React from "react"
import { useLayoutEffect } from "react"
import { MotionValue } from "framer"
import { throttle } from "./throttle"
export function useMotionCallback<K>(
parents: (MotionValue | number | boolean)[],
callback: (...parents) => K,
throttleStep = 16
) {
React.useEffect(() => {
const handleChange = () =>
throttle(callback(...parents.map(toValue)), throttleStep)
handleChange()
const removers = parents
.map(v => isMotionValue(v) && v.onChange(handleChange))
.filter(v => v) as (() => void)[]
return () => removers.forEach(fn => fn())
}, [...parents, callback])
}
// HELPERS
export const isMotionValue = (value: any): value is MotionValue => {
return value instanceof MotionValue
}
const toValue: <T>(v: MotionValue<T> | T) => T = v =>
isMotionValue(v) ? v.get() : v
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment