DEV Community


Posted on • Updated on

Simple Animations with React Hooks

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(
    const reset = () => setStartTime(
    useEffect(() => {
        let queuedFrame
        const frame = () => {
            const now = - startTime
            if (now < duration) queuedFrame = requestAnimationFrame(frame)
            setProgress(Math.min(1, now / duration))
        return () => cancelAnimationFrame(queuedFrame)
    }, [startTime, duration])
    return [progress, reset]
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

thecyberronin profile image

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!

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.