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 installation fsevents install errors when using Gatsby

If you’re using Gatsby, you might have noticed a rather lengthy, unhelpful message in your terminal when you run yarn install or yarn add that relates to fsevents. While Yarn will tell you this is okay because the dependency is “optional... Continue →