feat: add useTypewriter hook

This commit is contained in:
MBO-Tech-IT 2026-04-02 01:17:06 +02:00
parent c5a982abc0
commit 2d1f21efe7
1 changed files with 32 additions and 0 deletions

32
hooks/useTypewriter.ts Normal file
View File

@ -0,0 +1,32 @@
"use client";
import { useEffect, useState } from "react";
export function useTypewriter(words: string[], typingSpeed = 80, deletingSpeed = 40, pauseMs = 2000) {
const [displayed, setDisplayed] = useState("");
const [wordIndex, setWordIndex] = useState(0);
const [isDeleting, setIsDeleting] = useState(false);
useEffect(() => {
const current = words[wordIndex % words.length];
const timeout = setTimeout(() => {
if (!isDeleting) {
setDisplayed(current.slice(0, displayed.length + 1));
if (displayed.length + 1 === current.length) {
setTimeout(() => setIsDeleting(true), pauseMs);
}
} else {
setDisplayed(current.slice(0, displayed.length - 1));
if (displayed.length - 1 === 0) {
setIsDeleting(false);
setWordIndex((i) => i + 1);
}
}
}, isDeleting ? deletingSpeed : typingSpeed);
return () => clearTimeout(timeout);
}, [displayed, isDeleting, wordIndex, words, typingSpeed, deletingSpeed, pauseMs]);
return displayed;
}