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

Fix ESLint crashing on rest operator: “Cannot read property ‘type’ of undefined”

This is a bit of an obscure one, but I tend to use the same dev tooling configuration (Prettier, ESLint, Babel, etc) for multiple projects so I’m likely to run into this again. I encountered this in the middle of a project after a VSCode... Continue →