0

Suppose I have the following simple app:

const App = (props) => {
  const [count, setCount] = useState(0);

  useEffect(() => {
    console.log("before setting ", count);
    setCount(count + 1);
    console.log("set to ", count);
  }, []);
  return <div>hello</div>;
}

The expected result is:

before setting 0
set to 0

but the actual result is:

before setting 0
set to  0
before setting  0
set to  0

I do not understand two things:

  1. why does the useEffect function run twice?
  2. why does not setting the count value actually set it?

Thank you in advance!

BillTheKid
  • 377
  • 1
  • 13
  • `setCount()` does not update the `count` immediately: React batches these updates. If you want to log the new value of `count`, then use another `useEffect` hook that only has `count` in its dependency array. – Terry Sep 30 '22 at 11:21
  • 1. If the `useEffect` is running twice with `[]` it's likely your in debug mode, recent versions of React added this ``, in production this doesn't happen. – Keith Sep 30 '22 at 11:26
  • Re #1: https://reactjs.org/docs/strict-mode.html Re #2: https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous – T.J. Crowder Sep 30 '22 at 11:27
  • 1
    Thank you guys for the information. My questions are answered! – BillTheKid Sep 30 '22 at 11:31

0 Answers0