React hook useState(初始化函数)被调用了两次,即使根本没有改变数据?

Reack hook useState (initializer function) called twice, even without altering the data at all?

这里in this example我只是用初始化函数调用useState

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>
  );
}

正如您在控制台中看到的,useState 函数被调用了两次。这是正常现象吗?

这是由于 Strict Mode 包裹了您的 App

在严格模式下,React 有意运行一些生命周期方法两次以帮助检测错误。

来自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.