feat: initialize reactjs project using vite
This commit is contained in:
60
src/hooks/useTypingEffect.ts
Normal file
60
src/hooks/useTypingEffect.ts
Normal file
@@ -0,0 +1,60 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
|
||||
interface UseTypingEffectOptions {
|
||||
words: string[];
|
||||
typingSpeed?: number;
|
||||
deletingSpeed?: number;
|
||||
pauseDuration?: number;
|
||||
}
|
||||
|
||||
export function useTypingEffect({
|
||||
words,
|
||||
typingSpeed = 100,
|
||||
deletingSpeed = 50,
|
||||
pauseDuration = 2000,
|
||||
}: UseTypingEffectOptions) {
|
||||
const [currentWordIndex, setCurrentWordIndex] = useState(0);
|
||||
const [currentText, setCurrentText] = useState('');
|
||||
const [isDeleting, setIsDeleting] = useState(false);
|
||||
const [isPaused, setIsPaused] = useState(false);
|
||||
|
||||
const tick = useCallback(() => {
|
||||
const currentWord = words[currentWordIndex];
|
||||
|
||||
if (isPaused) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (isDeleting) {
|
||||
setCurrentText(currentWord.substring(0, currentText.length - 1));
|
||||
|
||||
if (currentText.length === 0) {
|
||||
setIsDeleting(false);
|
||||
setCurrentWordIndex((prev) => (prev + 1) % words.length);
|
||||
}
|
||||
} else {
|
||||
setCurrentText(currentWord.substring(0, currentText.length + 1));
|
||||
|
||||
if (currentText === currentWord) {
|
||||
setIsPaused(true);
|
||||
setTimeout(() => {
|
||||
setIsPaused(false);
|
||||
setIsDeleting(true);
|
||||
}, pauseDuration);
|
||||
}
|
||||
}
|
||||
}, [currentText, currentWordIndex, isDeleting, isPaused, words, pauseDuration]);
|
||||
|
||||
useEffect(() => {
|
||||
const speed = isDeleting ? deletingSpeed : typingSpeed;
|
||||
const timer = setTimeout(tick, speed);
|
||||
return () => clearTimeout(timer);
|
||||
}, [tick, isDeleting, typingSpeed, deletingSpeed]);
|
||||
|
||||
return {
|
||||
text: currentText,
|
||||
isTyping: !isDeleting && !isPaused,
|
||||
isDeleting,
|
||||
currentWordIndex,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user