Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we use object destructuring for useState() in reactjs hooks?

As from the documentation from Hooks in Reactjs,

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

they use array destructuring. Can we use object destructuring in place of array destructuring?

like image 822
Melvin George Avatar asked Jan 01 '23 16:01

Melvin George


2 Answers

I totally agree with answer given by @Patrick. Since react team implemented it adhere to all use cases. There's no need actually to put return values in object since it doesn't need to access it via keys or later need to update. One edge here is Destructuring part is way more easy for arrays than objects.

As we have seen const [count, setCount] = useState(0); we can use any name for count and setCount. In Objects we need to do it like this:

// grab the state value and setState func but rename them to count and setCount
   const { stateValue: count, setState: setCount } = useState(0);

in arrays:

// grab in order and rename at the same time
   const [count, setCount] = useState(0);
like image 64
Sakhi Mansoor Avatar answered Jan 04 '23 05:01

Sakhi Mansoor


useState returns an array, so no, in this case, you have to use array destructuring.

To clarify, this doesn't mean that all React hook functions need to return an array.

If you create your own hook, you can have it return whatever you like, including an object, which you can destructure.

like image 24
Patrick Hund Avatar answered Jan 04 '23 04:01

Patrick Hund