reactjs – Why does updating state inside useEffect sometimes cause infinite renders?

I’m using React hooks and ran into something I don’t quite get. If I update state inside a useEffect, React sometimes goes into an infinite render loop.

I tried this:

import { useEffect, useState } from "react";

function Counter() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    if (count < 5) {
      setCount(count + 1);
    }
  }, [count]);

  return 

Count: {count}

; }

I expected this to run until count reaches 5 and then stop. Instead, React complains about too many renders.
What’s the right way to update state in useEffect without creating this infinite loop?

Read more here: Source link