使用 hook useState 和 declare variable 的区别

Difference between using hook useState and declare variable

有什么区别

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

function Example() {
  const count = 0;

关于计数变量的语义?

除了setCount方法的存在,使用useState hook还有什么好处?

主要原因是,如果您在没有 useState 的计数的情况下使用 setCount,视图将不知道它必须 re-render,它们都在一起所以它知道如何同步。

每次使用 setCount 时,它都会再次进行完整渲染。

import React, { useState } from "react";
import ReactDOM from "react-dom";

import "./styles.css";

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

  function onClick() {
    setCount(count+1);
  }

  return (
    <div className="App">
      <h1 onClick={onClick}>{count}</h1>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
import React, { useState } from "react";
import ReactDOM from "react-dom";

import "./styles.css";

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

  function onClick() {
    setCount(count+1);
  }

  return (
    <div className="App">
      <h1 onClick={onClick}>{count}</h1>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);