DEV Community

loading...

Simple Animations with React Hooks

spaciecat profile image Spacie Updated on ・1 min read

Hi DevPeeps™! 👋

I just posted my first video tutorial (also my first youtube video in general)!

It's about using react hooks to create simple animations!

I've been getting really into hooks lately (especially linking them to other web APIs), so expect more hooks videos in the near future!

Also, if anyone has any feedback on the video I'd really love to hear it!
I'm quite new to video production and need all the advice I can get!

Thanks for reading and/or watching!


function useAnimation(duration) {
    const [progress, setProgress] = useState(0)
    const [startTime, setStartTime] = useState(Date.now())
    const reset = () => setStartTime(Date.now())
    useEffect(() => {
        let queuedFrame
        const frame = () => {
            const now = Date.now() - startTime
            if (now < duration) queuedFrame = requestAnimationFrame(frame)
            setProgress(Math.min(1, now / duration))
        }
        frame()
        return () => cancelAnimationFrame(queuedFrame)
    }, [startTime, duration])
    return [progress, reset]
}
Enter fullscreen mode Exit fullscreen mode

Discussion (2)

pic
Editor guide
Collapse
thecyberronin profile image
Ronin

The code is pretty sweet and your explanations seem good. The only thing that I really had any gripes with was the background sounds/music. The slight dinging playing from my laptop speakers were kind of distracting.

I could follow the code the way it was explained and seemed to make sense, great video!

Collapse
stephencweiss profile image
Stephen Charles Weiss

Very cool! The one part that tripped me up was the use of requestAnimationFrame.

Looks like this part of the browser's API, but it was just introduced without a lot of discussion which caught me off guard.

developer.mozilla.org/en-US/docs/W...