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.
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);
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With