Last active
January 25, 2019 18:31
-
-
Save Saifadin/4a2d21e376a6517b5800779a0e7807fc to your computer and use it in GitHub Desktop.
Typewriter like "animation" for a string | Hooks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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