Why React Hook useState uses const and not let

Nac*_*cho 25 javascript ecmascript-6 reactjs react-hooks

The standard way to use a React useState Hook is the following:

const [count, setCount] = useState(0);
Run Code Online (Sandbox Code Playgroud)

However this const count variable is clearly going to be reassigned to a different primitive value.

Why then is the variable not defined as let count?

Fel*_*ing 35

clearly going to be reassigned to a different primitive value

Not really. When the component is rerendered, the function is executed again, creating a new scope, creating a new count variable, which has nothing to do with the previous variable.

Example:

let _state;
let _initialized = false;
function useState(initialValue) {
  if (!_initialized) {
    _state = initialValue;
    _initialized = true;
  }
  return [_state, v => _state = v];
}

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

  console.log(count);
  setCount(count + 1);
}

Component();
Component(); // in reality `setCount` somehow triggers a rerender, calling Component again
Component(); // another rerender
Run Code Online (Sandbox Code Playgroud)

Note: Hooks are way more sophisticated and are not actually implemented like this. This is just to demonstrate a similar behavior.

  • @Daniel:可能,但它们也可能指这样一个事实:当对象或数组存储在状态中并且您想要更改它们时,您应该创建对象或数组的副本。即 `setList([...list, newElement])` 和 not(!) `list.push(newElement); 设置列表(列表);`。 (2认同)
  • @GeorgeMeijer:仅当没有其他内容引用它时。例如,组件可以包含一个“useCallback”钩子,其回调不会在每次渲染时发生变化。在渲染组件的任何时候,回调都可能不会改变,而是使用先前渲染的回调,这当然会以某种方式保留先前的作用域/执行上下文。 (2认同)

ton*_*ony 5

const 防止在同一范围内重新分配引用的值。

来自MDN

这并不意味着它持有的值是不可变的,只是变量标识符不能重新分配。

常量不能与同一作用域内的函数或变量共享其名称。

  • 虽然原始值是不可变的,所以问题更多的是解释 const 数字如何改变? (3认同)