I have seen a hook state initalize in this way.
const colors = [
{ value: 'ocean', text: 'Ocean', color: '#00B8D9' },
{ value: 'blue', text: 'Blue', color: '#0052CC' },
{ value: 'purple', text: 'Purple', color: '#5243AA' },
]
const [{ formBasicUsageExample }, setState] = useState({ formBasicUsageExample: colors[0] })
This looks strange to me. I never see people use {} to surround a state here. How to understand the {} around formBasicUsageExample? What is the effect here
I understand the concept of destructuring, and it looks it may be deal with that. But I dont get it in such context(normally in para list). Appreciate if a basic example provide to understand it.
>Solution :
Javascript Object destructuring
You are setting the state variable value with { formBasicUsageExample: { value: 'ocean', text: 'Ocean', color: '#00B8D9' }}
Then using javascript object destructuring to only fetch the value of formBasicUsageExample key.
const colors = [
{ value: 'ocean', text: 'Ocean', color: '#00B8D9' },
{ value: 'blue', text: 'Blue', color: '#0052CC' },
{ value: 'purple', text: 'Purple', color: '#5243AA' },
]
const [{ formBasicUsageExample }, setState] = useState({ formBasicUsageExample: colors[0] });
Here, formBasicUsageExample contains :
{ value: 'ocean', text: 'Ocean', color: '#00B8D9' }
If there is no {} provided,
const colors = [
{ value: 'ocean', text: 'Ocean', color: '#00B8D9' },
{ value: 'blue', text: 'Blue', color: '#0052CC' },
{ value: 'purple', text: 'Purple', color: '#5243AA' },
]
const [formBasicUsageExample , setState] = useState({ formBasicUsageExample: colors[0] });
Here, formBasicUsageExample contains :
{ formBasicUsageExample: { value: 'ocean', text: 'Ocean', color: '#00B8D9' }}
Simple Javascript example:
let person = { firstName: 'John', lastName: 'Doe'};
const {firstName} = person;
console.log(firstName);