0

Below you can see some codesandbox example of react component , which just make simple count change(counter). I just try to log my new counter value , and I see , that it logs it twice on each button click, but why ? If I only change it once . Is there any explanation of this ?

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

  const onClick = useCallback(() => {
    setCount((prev) => prev + 1);
  }, []);

  console.log(count, "rerender");
  return (
    <div className="App">
      <h1>{count}</h1>

      <button onClick={onClick}>Click</button>
    </div>
  );
}
react: 18.0.0
react-dom: 18.0.0

Edit loving-architecture-sul1s8

Andrey Radkevich
  • 2,328
  • 2
  • 17
  • 38
  • 1
    Your app is under StrickMode. So in development mode, re-rendering occurs twice. But in production, it will render once. No worries. Please refer to [this](https://stackoverflow.com/questions/61254372/my-react-component-is-rendering-twice-because-of-strict-mode) and [React Strict mode](https://reactjs.org/docs/strict-mode.html) – Liki Crus Apr 17 '22 at 12:59

0 Answers0