useTypewriter
A hook that simulates typing of a string.
Usage
1 2 3 4 5 6 7
import useTypewriter from "@/hooks/use-typewriter"; export default function Example() { const value = useTypewriter("Hello, world!", 2000); return <div>{value}</div>; }
Installation
npx shadcn add "https://registry.niels.foo/use-typewriter.json"
Source
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;
}