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

Case Sensitivity with `localeCompare` in JavaScript

I recently ran into a bug using code like the following: someArray.sort((a, b) => a.name.localeCompare(b.name)) At a glance this seems fine—localCompare enjoys fantastic browser support, and as the name suggests, it isn’t... Continue →