Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why React useState return const array

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.

like image 314
bunny Avatar asked Mar 18 '19 05:03

bunny


People also ask

Why does useState return an array instead of object?

Going back to the useState hook, it returns its variables in an array because it is likely that we're going to use that hook more than once per component. We need to be able to instantiate that hook several times but each instance has a different name. Example: const [val, setVal] = useState(0);

Does useState return array?

useState returns an array with exactly two values: The current state. During the first render, it will match the initialState you have passed. The set function that lets you update the state to a different value and trigger a re-render.

Why is const used with useState?

What does useState return? It returns a pair of values: the current state and a function that updates it. This is why we write const [count, setCount] = useState() . This is similar to this.state.count and this.setState in a class, except you get them in a pair.

Should custom hook return array or object?

Returning an array is a best practice when returning multiple values from a custom hook, because React's built-in Hooks -- in the case of returning multiple values -- make use of arrays and therefore array destructuring as well.


1 Answers

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.

like image 179
Shubham Khatri Avatar answered Sep 25 '22 01:09

Shubham Khatri