Created
September 26, 2019 13:25
-
-
Save steveruizok/87464a55de1687ca8d09a73abda33ac6 to your computer and use it in GitHub Desktop.
Call a function whenever a motion value changes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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