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

Consistent Date Formatting in Ruby on Rails 5+

If you’ve ever dealt with dates in Rails, particularly accepting dates from user input and then displaying them, you’re familiar with two clunky experiences: The awful default month, day, year, hour, minute, second dropdowns The complete... Continue →