niels segers

use-typewriter

A hook to emulate a typewriter effect of a specified string. Use it to eg. display a dynamic input placeholder for a chatbot.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 import { useEffect, useState } from 'react'; export default function useTypewriter(text: string, speed = 50) { const [value, setValue] = useState(''); /** * In a short interval add a letter to mimic typing of the placeholder */ useEffect(() => { const interval: NodeJS.Timeout = setInterval(() => { if (value === text) { clearInterval(interval); return; } // Server revalidated with a different string, so don't bother continuing the current typewriter if (!text.startsWith(value)) { return clearInterval(interval); } // Add the next letter const updated = value + text[value.length]; setValue(updated); }, speed); return () => clearInterval(interval); }); return value; }