Kevin Powell - CommunityKP-C
Kevin Powell - Community11mo ago
17 replies
vince

Confused by useEffect in React

I'm confused on how useEffect actually works. I know useEffect is used to trigger some sort of 'side effect' after the changes are committed to the browser. I'm creating a typewriter effect for an example here and I'm confused on the dependency array of useEffect. Obviously, whatever you pass to the dependency array is what will call the useEffect again if said value changes / updates. But why does this typewriter effect not work if I remove
index
from the dependency array?

If I remove it from the dependency array, it'll print out the first letter countless times. It's not actually updating the index state and instead using the old value. My understanding of useEffect is that as long as it reruns it'll use the updated state values in the component, even if it's not in the dependency array. This doesn't seem to be the case. So if any value is needed in useEffect I must pass it to the dependency array if I need its updated values after rerenders?

Example:
export const useTypewriter = (text, delay = 500) => {
  const [display, setDisplay] = useState("");
  const [index, setIndex] = useState(0);

  useEffect(() => {
    const timeoutId = setInterval(() => {
      if (index < text.length) {
        setDisplay((previous) => previous + text[index]);
        setIndex((previous) => previous + 1);
      }
    }, delay);

    return () => clearTimeout(timeoutId);
  }, [text, delay, index]); // If I remove index here it'll print out the first letter over and over

  return display;
};
Was this page helpful?