import { useEffect, useState } from "react"; export default function useIsTyping() { const [isTyping, setIsTyping] = useState(false); const [isKeyPressed, setIsKeyPressed] = useState(false); const [countdown, setCountdown] = useState(5); const startTyping = () => { setIsKeyPressed(true); setCountdown(5); setIsTyping(true); }; const stopTyping = () => { setIsKeyPressed(false); }; const cancelTyping = () => { setCountdown(0); }; useEffect(() => { let interval: NodeJS.Timeout | undefined; if (!isKeyPressed) { interval = setInterval(() => { setCountdown((c) => c - 1); }, 1000); } else if (isKeyPressed || countdown === 0) { if (interval) { clearInterval(interval); } } if (countdown === 0) { setIsTyping(false); } return () => { if (interval) { clearInterval(interval); } }; }, [isKeyPressed, countdown]); return { cancelTyping, isTyping, startTyping, stopTyping }; }