Why do we use array destructuring (square brackets notation) in `useState`?
When we declare a state variable with useState
, it returns a pair — an array with two items. The first item is the current value, and the second is a function that updates the value. Using [0] and [1] to access them is a bit confusing because they have a specific meaning. This is why we use array destructuring instead.
For example, the array index access would look as follows:
var userStateVariable = useState('userProfile'); // Returns an array pairvar user = userStateVariable[0]; // Access first itemvar setUser = userStateVariable[1]; // Access second item
Whereas with array destructuring the variables can be accessed as follows:
const [user, setUser] = useState('userProfile');
March 31, 2022
1973
Read more
What is React?
November 06, 2022
ReactJSHow to programmatically trigger click event in React?
November 06, 2022
ReactJS