what does {} mean in hook state initialization react

Viewed 36

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.

2 Answers

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);

What's being done is technically destructuring.

It's just being done in a confusing manner. What formBasicUsageExample refers to on the left hand side of the assignment is the value in the returned object associated with that key, so in our case it will be whatever the value of colors[0] is.

Related