Search code examples
javascriptreactjsreact-hookssetinterval

react use effect not stopping on exit condition


I'm trying to make a typewriter effect from scratch with the help of the setInterval function but when the word is done being typed the component remounts again with every interval.

export default function Typewriter() {
  const name: string = 'Mouhib Ouni';
  const [word, setWord] = useState<string>('');

  useEffect(() => {
    if (word.length < 11) {
      console.log(word.length);
      setInterval(() => {
        setWord(word + name[word.length]);
      }, 1000);
    }
  }, [word]);

  return <div>{word}</div>;
}

Solution

  • Using setInterval will create waves of looping, which is not what you want. Using a setTimeout will kick off a 1 second delay followed by your setWord function. With setInterval, using the cleanup function in your useEffect is mandatory. With setTimeout, I'd say it's good housekeeping, but not totally needed. Here is the modified useEffect:

    useEffect(() => {
      let timeout;
      
      if (word.length < 11) {
        console.log(word.length);
        timeout = setTimeout(() => {
          setWord(word + name[word.length]);
        }, 1000);
      }
    
      return () => clearTimeout(timeout);
    }, [word]);
    

    demo