Making Typing Animation with React Hooks

Making Typing Animation with React Hooks

Ever wondered how to make words auto-type themselves onto a page? In this article, we shall go through a step-by-step tutorial on how to do so in your React app like this one below:


Note: It is smoother than it looks, the frame rate as I recorded the screen was bad.

Some Prerequisites you need:

  • Basic understanding of React
  • Basic understanding of useState and useEffect React Hooks

Step 1: Import hooks

In our new React app project, let's import the hooks we will need: useState and useEffect.

import React, { useState, useEffect } from "react"

Step 2: Initialize States

We are going to initialize 3 states:

  • text: This is the current text that is displayed on the page.
  • fullText: This is the final text we want to see after everything is typed out on the page.
  • index: This is the current index of the text that is being displayed on the page.

So we will initialize the states with useState as follows:

const [text, setText] = useState("")
const [fullText, setFullText] = useState(
    "Your source of leading edge water and air treatment technology since 1994."
const [index, setIndex] = useState(0)

Step 3: Text Animation

To implement our text animation, we want our text to show characters of fullTextone at a time. We will use index to track which character are we currently displaying from fullText.

We can create a useEffect function like so:

useEffect(() => {
    if (index < fullText.length) {
      setTimeout(() => {
        setText(text + fullText[index])
        setIndex(index + 1)
      }, 40)
  }, [index])

When the current index is less than fullText length, we will use setTimeOut() to continuously add the next character of fullText to our text then increase the index by one.

This way, text will be animated one character at a time.

Step 4: Render text

Now we simply need to include text in the render function like:


And that's it!

And that's how the text will auto type itself onto the page. Thanks for reading. I hope it is helpful. Don't forget to like or share if it is and let me know if you have questions in the comments below. Till next time, cheers!

Did you find this article valuable?

Support Victoria Lo by becoming a sponsor. Any amount is appreciated!