1

maybe some of you can open my eyes.

I don't understand why in this code: https://codesandbox.io/s/use-state-renders-twice-6r1xl component App renders twice when mounted and clicking the button (console.log is called twice)

code:

export default function App() {
  const [clicked, setClicked] = React.useState(false);
  const handleClick = () => setClicked(!clicked);
  console.log(clicked);
  return <button onClick={handleClick}>click</button>;
}

result:

false
false
true
true

it's just a functional component hooking useState!

Vicens Fayos
  • 740
  • 1
  • 5
  • 18
  • Does this answer your question? [Why does useState cause the component to render twice on each update?](https://stackoverflow.com/questions/61578158/why-does-usestate-cause-the-component-to-render-twice-on-each-update) – jonrsharpe May 14 '20 at 15:09

1 Answers1

4

It is because of React.StrictMode and this only happens in development. If you remove React.StrictMode you will get only 1 log.

For more details, check this thread on react repo:

https://github.com/facebook/react/issues/15074

Also check React docs: https://reactjs.org/docs/strict-mode.html#detecting-unexpected-side-effects

Check the app without StrictMode here: https://codesandbox.io/s/use-state-renders-twice-3vroc

Hope this helps!

Yash Joshi
  • 2,586
  • 1
  • 9
  • 18