useTypedText React Hook

I needed to add a text-being-typed effect to a complex animation recently, and instead of cluttering up the more nuanced parts of the animation with the typing animation, I wrote a quick React Hook that takes the final string and returns the currently typed text. This seems like the sort of thing I’ll use again, and hopefully it’ll help someone else as well:

import { useState, useEffect } from "react"

export default (finalText, delay = 250) => {
  const [state, setState] = useState(finalText.slice(0, 1))

  useEffect(() => {
    const deferredActions = finalText.split("").map((char, index) => {
      if (index) {
        return window.setTimeout(() => {
          setState(finalText.slice(0, index + 1))
        }, delay * index)
      }
    })

    return () => {
      deferredActions.forEach(timeout => {
        timeout && window.clearTimeout(timeout)
      })
    }
  }, [finalText, delay])

  return state
}

That’s all!

 
4
Kudos
 
4
Kudos

Now read this

Fixing Broken `gem install` from Xcode update

Quick tip: upgrading to Xcode 8.0 on a Mac with existing dev tools installed results in compilation failures due to the build tool license. You need to agree to the new license before proceeding, which requires running with admin... Continue →