Skip to content

useState

一句话解释

useState 是 Hook 那个 lets 函数组件持有 and 更新局部状态, returning current 值 and setter 函数.

用大白话说

useState is the most commonly used Hook. It declares a piece of state inside a function component. You call it with an initial value, and it returns an array with two elements: the current state value and a function to update it.

const [数量, setCount] = useState(0) — here 数量 starts at 0, and setCount is the updater. When you call setCount(5), React schedules a re-render with the new value.

Important behaviors: the setter can take a new value or an updater function setCount(prev => prev + 1) (useful when the new state depends on the old). State updates are asynchronous — calling the setter does not immediately change the variable. Also, unlike 这个.状态 in class components, useState does not merge update objects automatically; you must spread previous state yourself when updating objects.

示例

jsx
function Toggle() {
  const [on, setOn] = useState(false);
  return (
    <button onClick={() => setOn(!on)}>
      {on ? "ON" : "OFF"}
    </button>
  );
}

on 开始 as 假. 每个点击 flips 它. React re-渲染 button 使用新 label 之后每个更新.

常见混淆

  • 容易混淆的对象: useReducer

    关键区别: useState 是 for 简单 independent 值. useReducer 是 for 复杂状态 logic involving 多个 sub-值 or 当下一个状态 depends on 上一个 one in 非-trivial 方式.

相关术语

相关资源

相关课程

  • 状态

    学习 useState in 深度.

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回术语表