Skip to content

Instantly share code, notes, and snippets.

@Saifadin
Last active January 25, 2019 18:31
Show Gist options
  • Save Saifadin/4a2d21e376a6517b5800779a0e7807fc to your computer and use it in GitHub Desktop.
Save Saifadin/4a2d21e376a6517b5800779a0e7807fc to your computer and use it in GitHub Desktop.
Typewriter like "animation" for a string | Hooks
import { useState, useEffect } from 'react';
export const useTypeWriter = (text, startNow = true, speed = 100, skip) => {
const [toBeTyped] = useState(text);
const [displayedText, setDisplayedText] = useState('');
const [isDone, setIsDone] = useState(false);
const [intervalId, setIntervalId] = useState(null);
useEffect(
() => {
if (skip) return;
if (displayedText.length === toBeTyped.length) {
clearInterval(intervalId);
setIsDone(true);
} else {
const interval = setInterval(() => {
if (displayedText.length < toBeTyped.length && startNow) {
setDisplayedText(toBeTyped.substring(0, displayedText.length + 1));
}
}, speed);
setIntervalId(interval);
}
return () => clearInterval(intervalId);
},
[displayedText, startNow]
);
return [displayedText, isDone || false];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment