10

I'm using useState() in function component and first render is calling twice. Is it correct or mistake? If it is correct why does it render twice? setCount renders the component twice too.

function Example() {
  const [count, setCount] = useState(0);
  console.log("render");

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

ReactDOM.render(<Example />, document.getElementById('uu5'));

Thanks

skyboyer
  • 22,209
  • 7
  • 57
  • 64
Ondřej Čapek
  • 123
  • 1
  • 6

3 Answers3

15

According to react docs, it's an intentional feature to help you to detect unexpected side effects if you're using StrictMode

Strict mode can’t automatically detect side effects for you, but it can help you spot them by making them a little more deterministic. This is done by intentionally double-invoking the following functions:

  • Class component constructor, render, and shouldComponentUpdate methods
  • Class component static getDerivedStateFromProps method
  • Function component bodies
  • State updater functions (the first argument to setState)
  • Functions passed to useState, useMemo, or useReducer

Note: This only applies to development mode. Lifecycles will not be double-invoked in production mode.

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

Jorge Arimitsu
  • 233
  • 2
  • 10
2

Problem is in React DevTools. When console is closed, component is rendered just one times. But if you open React DevTools and reload the page, render will be shown two times. Open example and try it. (React 16.8.3)

Ondřej Čapek
  • 123
  • 1
  • 6
1

remove <React.StrictMode> wrapper in the index.js file

Стас Рябцев
  • 1,318
  • 4
  • 19
  • 36