Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

what does {} mean in hook state initialization react

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading