2

i wrote the simple code as follows

import React, { useState, useEffect } from "react";

export default function App() {
  const [count, setCount] = useState(1);

  useEffect(() => {
    setCount(2);
  }, [count]);

  console.info("render: ", count);
  return <div>{count}</div>;
}

the console output as

render:  1
render:  2
render:  2

why "render:2" output twice

Yao Tao
  • 59
  • 8

1 Answers1

3

The issue is that you are unconditionally updating state that you are using as a dependency.

This behavior isn't unexpected.

See Bailing out of a state update

If you update a State Hook to the same value as the current state, React will bail out without rendering the children or firing effects. (React uses the Object.is comparison algorithm.)

Note that React may still need to render that specific component again before bailing out. That shouldn’t be a concern because React won’t unnecessarily go “deeper” into the tree. If you’re doing expensive calculations while rendering, you can optimize them with useMemo.

The count is 1 on the initial render, the first log. useEffect hook runs and enqueues a state update and the update is processed.

The count is 2 on the next render, the second log. count state value updated so useEffect hook callback runs and enqueues another state update to the same value and the update is processed.

The count is still 2 on the next render, the third log. count state hasn't changed so the useEffect hook callback isn't triggered.

Drew Reese
  • 165,259
  • 14
  • 153
  • 181