Reputation: 3
I have my code as :
export default class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
value: []
};
}
useValue() {
myValue = this.state.value;
doSomething(myValue);
}
}
And I noticed that there are two way to use the value
in this.state
myValue = this.state.value;
and
const {value} = this.state;
So what is the difference between these two? Is there any benefits of using one against another? Thanks a lot!
Upvotes: 0
Views: 858
Reputation: 3444
Both syntaxes perform a similar function, but are useful for different reasons and have different names.
const {value} = this.state;
is called deconstruction. It's when you create a variable(s) from a JavaScript object's element. Within the context of ReactJS, it's commonly used when a developer wants to reference several state object elements without having to reference the state directly beyond the first line of the render method. Check out this link for more information on deconstruction. See my example below for pulling out multiple elements from the state object.
Example const { a, b, c } = this.state;
myValue = this.state.value;
is a standard assignment operator. It's a typical way to create a variable from a value. In this case, it happens to be an element of React's state object. You can read more about assignment operators here.
Upvotes: 1
Reputation: 311
The first example it's a simple assignment and the second one it's using object destructuring assignment (Docs).
The main differences when you use a destructuring assignment and a common variable assignment is that when you use the destructuring you can declare more variables in a single line. So let's say you have the following object:
const obj = {
foo1: 'someValue',
foo2: 'anotherValue',
foo3: 'lastValue',
};
And you need to have the 3 properties in different variables, you can do something like this:
const foo1 = obj.foo1;
const foo2 = obj.foo2;
const foo3 = obj.foo3;
With destructuring assignment you would be able to do something like:
const { foo1, foo2, foo3 } = obj;
As you can see it's much more simpler to read and you are writing less code to declare the variables. There's a lot of other things that you can do with destructuring but in this particular case it's the main reason.
Upvotes: 1