DEV Community

Bay Area Ninja
Bay Area Ninja

Posted on

#help useRef within useEffect

my Goal: Is to create a simple effect that prints out a string one letter at a time.

example: string = "TEXT". it should print T E X T

Whats currently being printed is: T X T undefined

my code:

`const [placeholder, setPlaceholder] = useState('');
const
string = 'TEXT',
index = useRef(0);

useEffect(() => {
function showChar() {
setPlaceholder(prev => prev + string[index.current]);
console.log(index.current)
index.current++;
}
if (index.current < string.length) {
let addChar = setInterval(showChar, 500);
return () => clearInterval(addChar);
}
}, [placeholder]);

return (


{placeholder}

)

export default App;`

Top comments (0)