Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructuring state in React render

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.

like image 969
Pav Sidhu Avatar asked Feb 17 '17 21:02

Pav Sidhu


People also ask

How do you Destructure a state in React?

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.

What is Destructuring in React example?

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.

Why we use Destructuring in React?

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.

Should I Destructure props React?

js. While working with React. js components, there are two ways using which you can retrieve/access the component props.


1 Answers

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.

like image 190
Razvan Alex Avatar answered Sep 20 '22 15:09

Razvan Alex