0.1.2 • Published 4 years ago
use-request-animation-frame v0.1.2
use-request-animation-frame
React hook for easy access requestAnimationFrame browser API. Written with Typescript and provides you with handy animation duration control.
Usage
Basic usage requres only one handler:
const nextAnimationFrameHandler = (progress: number) => {...}; useRequestAnimationFrame(nextAnimationFrameHandler);With this
nextAnimationFrameHandlerwill be called every frame andprogressvariable will always have value 1, so you wont need it in yournextAnimationFrameHandlerUsage with
duration:const myAnimatedDiv = React.useRef(); const nextAnimationFrameHandler = (progress: number) => { if(myAnimatedDiv.current) myAnimatedDiv.current.style.left = progress * 100 + 'px' //... } useRequestAnimationFrame(nextAnimationFrameHandler, { duration: 2000 })In this case
nextAnimationFrameHandlerwill be called every frame withprogresscalculated based on time when first animation frame was shownUsage with
shouldAnimate:const [shouldAnimate, setShouldAnimate] = React.useState(false); const nextAnimationFrameHandler = (progress: number) => {...}; useRequestAnimationFrame(nextAnimationFrameHandler, { duration: 2000, shouldAnimate });In this case
nextAnimationFrameHandlerwill not be called initially and animation will start only aftersetShouldAnimate(true)call
⭐ Happy Hacking ⭐
You can find more implementation details in my article