Destructuring in React

Olesya Miller
2 min readJan 11, 2021

Us programmers know that we have to keep our code as concise and dry as possible at all times. That’s why I thought it would be a good idea to write about destructuring in React.

What is destructuring? Destructuring was introduced in ES6. It is a way of extracting props and giving those props much shorter names. It copies the desired items from data structures into variables. Destructuring lets us keep our code very clean and organized. Let’s look at an example.

In my Airbnb clone app I have a functional component for Listing. I mount that component in my Listings component and pass it a prop of listing. Each listing has image url, title, location and id. Instead of typing props.listing.img_url or props.listing.title, I destructure the props at the top of the component, before the return function

const Listing = (props) => {   const { listing: {id, img_url, location, title } } = props   return (      <div>         <Link to={`/listings/${id}`}>            <Image style={{ width: '18rem' }} src={img_url} alt={title}/>            <h4>{title}</h4> <strong>{location.name}</strong><br/>         </Link>     </div>   )}

Note that I’m destructuring the props two levels deep. If I do it this way

const {listing} = props

I will have to access each attribute of the object using dot notation

<Link to={`/listings/${listing.id}`}>   <Image style={{ width: '18rem' }} src={listing.img_url} alt={listing.title}/>   <h4>{listing.title}</h4> <strong>{listing.location.name}</strong>   <br/></Link>

From the examples above we can see that destructuring props two or three levels deep makes the code much cleaner!

We can also destructure props right in the parenthesis of a functional component, like this

const ListingShow = ({ listings, match }) => {...

Destructuring works very similarly in class components. In class components it goes inside the render function, right above the return function.

class Reviews extends Component {   render() {      const {reviews, listingId} = this.props      const associatedReviews = reviews.filter(review => review.listing_id === listingId);...

I hope you found this post useful! Happy coding!

--

--