Destructuring in React

Yuki Yao
Yuki Yao
Nov 7 · 3 min read
Photo by Clem Onojeghuo on Unsplash

I was first introduced to the concept of destructuring when I was learning ES6 in Javascript. I admit that destructuring exists in many other programmer’s code, but unfortunately, not in mine. This is mostly due to the fact that I am used to writing long, layer-over-layer code. “As long as my project works, refactoring can wait.”

The more features we want our app to have, the more code we would write. Our project folder got larger, the code page got longer, and I started to look for simplicity.

What is Destructuring?

Destructuring is a convenient way to extract multiple keys from an object or array simultaneously and assign the values to local variables.

// For Arrayconst arr = ['one!', 'two!', 'three!', 'four!']
const [one, two, ...rest] = arr
// What does that mean?const arr = ['one!', 'two!', 'three!', 'four!'];
const one = arr[0],
two = arr[1],
rest = arr.slice(2);
// For Objectconst obj = {a: 'x', b: 'y', c: 'z'}
const {a, b, c} = obj
// What does that mean?const obj = { a: 'x', b: 'y', c: 'z' };
const a = obj.a,
b = obj.b,
c = obj.c;

We can also see array destructuring in React Hooks.

import React from 'react';const Counter = () => {  const [count, setCount] = React.useState(0)  return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
)
}
export default Counter;

We also used rest destructuring for splitting out part of an object.

const state = { 
counter: 1,
list: ['a', 'b']
}
// rest destructuring
const { list, ...rest } = state
console.log(rest)
// output: { counter: 1 }
console.log(list)
// output: ['a', 'b']

With React, it is really common to destructure props to pass to the child components. There are small differences between a class component and a functional component when destructuring props.

Class Component

class MovieCard extends React.Component {  render() {    return (
<div className="movie-card">
<img src={this.props.posterSrc} alt={this.props.title} />
<h2>{this.props.title}</h2>
<small>{this.props.genres.join(', ')}</small>
</div>
)
}
}

In the example above, we have a class component MovieCard. As we can see, we have used ‘this.props’ in several places. This is really DRY.

After destructuring, the code becomes shorter and cleaner. ⬇️

class MovieCard extends React.Component {  render() {  const {posterSrc, title, genres} = this.props  return (
<div className="movie-card">
<img src={posterSrc} alt={title} />
<h2>{title}</h2>
<small>{genres.join(', ')}</small>
</div>
)
}
}

Functional Component

// First wayconst AppComponent = (props) =>{const { data, loading, loadData } = props

/*
line above equals:
const data = props.data;
const loading = props.loadding;
const loadData = props.loadData;
*/
return <div>
<AnotherComponent >
</div>
}

Or, you can pass destructured props in the argument:

// Second wayconst AppComponent = ({ data, loading, loadData }) =>{

……

return <div>
<AnotherComponent/>
</div>
}

// If you have several props, you can write it like this for better readability:
const AppComponent = ({
data,
loading,
loadData
}
) =>{

……

return <div>
<AnotherComponent/>
</div>
}

Benefits of Destructuring

Destructuring definitely improves readability and provides shorter lines of code. It can also give us the flexibility so we have access only to the props we need on that file. It would be a big help for debugging as well.

I do believe that clean code is good code. Destructure and happy Reacting!

Sources:
https://www.robinwieruch.de/javascript-fundamentals-react-requirements#destructuring-in-react
https://www.freecodecamp.org/news/the-basics-of-destructuring-props-in-react-a196696f5477/?source=post_page-----b1c295005ce0----------------------

Yuki Yao

Written by

Yuki Yao

#programming #photography

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade