'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?
Solution 1:[1]
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);
Solution 2:[2]
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.
Solution 3:[3]
You should not for useState
, but...
As @SakhiMansoor mentioned, naming variables become easy when destructuring array in case of setState
, because it's generic hook and you can use it for different data, eg:
const [count, setCount] = useState(0);
const [age, setAge] = useState(0);
...
But when creating custom hooks I usually prefer objects. Let's consider an example:
// If return an array
const [items, addItem, removeItem] = useItems();
// and only need `removeItem`, I write (I could easily forget one `,` here):
const [, , removeItem] = useItems();
// if I returned object, I would:
const { removeItem } = useItems();
When writing custom, specific hooks, I usually don't need to rename keys, so object works better in this case.
Solution 4:[4]
setDetails(prev => { return { ...prev, [e.target.name]:e.target.value } });
one of the best way.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Patrick Hund |
Solution 3 | karaxuna |
Solution 4 | subhajit das |