I see a lot of examples that show a React component that looks like this:
class MyComponent extends Component {
constructor(props) {
super(props)
this.state = {
foo: 'foo',
bar: 'bar'
}
}
render() {
const { foo, bar } = this.state
return <Text>{foo}{bar}</Text>
}
}
As you can see, the component's state has been destructured. I can see that the JSX looks cleaner, but it appears that it would be harder to know that a variables came from the components state. Is there any benefit of doing this in terms of best practices or is it just a preference?
Thanks.
Destructuring state Destructuring states is similar to props. Here is syntax to Destructuring states in React: import React, { Component } from 'react' class StateDemp extends Component { render() { const {state1, state2, state3} = this.
Destructuring is a convenient way of creating new variables by extracting some values from data stored in objects or arrays. To name a few use cases, destructuring can be used to destructure function parameters or this. props in React projects for instance.
We may have an array or object that we are working with, but we only need some of the items contained in these. Destructuring makes it easy to extract only what is needed.
js. While working with React. js components, there are two ways using which you can retrieve/access the component props.
Advantage: The code looks much cleaner especially if you need to reuse state values multiple times in a component.
Disadvantage: If you're making a module or open sourcing your code the destructed statement could cause confusions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With