3

Here in this example I simply call useState with an initializer function:

import React, { useState } from "react";
import "./styles.css";

export default function App() {
  const [data, setData] = useState(() => {
    console.log('Getting initial state...');

    return {};
  });

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

As you can see from console, useState function is called twice. Is there any reason for that, it's the normal behavior?

gremo
  • 47,186
  • 75
  • 257
  • 421

1 Answers1

7

This is caused by Strict Mode which is wrapping your App.

Under Strict mode react intentionally runs some lifecycle methods twice to help detect errors.

From the docs:

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.

thedude
  • 9,388
  • 1
  • 29
  • 30