最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why React useState return const array - Stack Overflow

programmeradmin1浏览0评论

I am currently learning React and React hook. A classic example of using useState is as below:

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

My question is why the returned array is const? I think at least the value of count is changed over time.

I am currently learning React and React hook. A classic example of using useState is as below:

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

My question is why the returned array is const? I think at least the value of count is changed over time.

Share Improve this question asked Mar 18, 2019 at 5:20 bunnybunny 2,0378 gold badges37 silver badges66 bronze badges 3
  • Possible duplicate of Javascript object bracket notation ({ Navigation } =) on left side of assign and What is destructuring assignment and its uses? – adiga Commented Mar 18, 2019 at 5:21
  • Possible duplicate of What is destructuring assignment and its uses? – Code Maniac Commented Mar 18, 2019 at 5:23
  • 2 You're not supposed to mutate state. In order to correctly update your values, you should use setCount() to update the value of count. I believe you may destructure it using let or var but using const helps prevent mutation. – Miroslav Glamuzina Commented Mar 18, 2019 at 5:24
Add a comment  | 

1 Answer 1

Reset to default 23

The value returned by useState is not a const array, rather its just an array which the user has decided to declare as const. Think of the above as

const stateValue = useState(0);
const count = stateValue[0];
const setCount = stateValue[1];

So in short, the syntax const [count, setCount] = useState(0); is an Array destructuring syntax.

Not its is declared as const because you are not reassigning count or setCount to something else in your code, instead just using setCount method to update the state count.


React authors decided to return an array with state value and state setter so that you can name it anything you want instead of using a pre-decided name while destructuring.

发布评论

评论列表(0)

  1. 暂无评论