Destructuring in Reactjs – Why use it?

What is Destructuring?

Destructuring JavaScript in Reactjs

Destructuring is a convenient way of accessing multiple properties stored in objects and arrays. It was introduced to JavaScript by ES6 ( version 6 of the ECMA Script programming language) and has provided developers with an increased amount of utility when accessing data properties in Objects or Arrays.

When used, destructuring does not modify an object or array but rather copies the desired items from those data structures into variables. These new variables can be accessed later on in a React component.

How to use it?

A common situation that I find myself using destructuring is in the render function of my React components. In these components, access to props can be made significantly easier using destructuring.

In the render function props are made more accessible by assigning them to new single worded variables.

This allows the use of props in a more readable format. And reduces the need to specify this.props for every property.

Lets take an example:

render() {
    return (
      <section>
        {this.props.loading ? (
          <div className="loader">
            <ClipLoader color={'white'} loading={this.props.loading} />
          </div>
        ) : (
          <div className="results">
            {this.props.error.errorHappened ? (
              <h1>{this.props.error.errorMsg}</h1>
            ) : (
                <div>No Error </div>
          </div>)
    </section>

Compare that to destructuring the props:

render() {
const { loading, errorMsg, errorHappened } = this.props
    return (
      <section>
        {loading ? (
          <div className="loader">
            <ClipLoader color={'white'} loading={loading} />
          </div>
        ) : (
          <div className="results">
            {errorHappened ? (
              <h1>{errorMsg}</h1>
            ) : (
                <div>No Error </div>
          </div>)
    </section>

Notice the reduction of the usage of this.props no longer is it unnecessarily recycled in the render function. And instead, more concise names of these properties are being used.

Default values

There are plenty of instances where the value extracted during  destructuring does not exist. In this situation, we can easily apply a default value to the newly declared properties.

const { loading, errorMsg, errorHappened = true } = this.props

In this case, errorHappened will be set to true if it is undefined in this.props.

Using different names

Similarly, a variable name that is not a carbon copy of the the property being destructured may want to be used. 

This is achieved, by reassigning the property like so:

const { loading: isLoading, errorMsg: userMessage,  errorHappened: errorExists = true } = this.props

The properties loadingerrorMsg, and  errorHappened have been destructured and reassigned as variables named isLoadinguserMessageand errorExists.

This is useful when the original data property names are not descriptive enough when used in the context of your React component.

What are the benefits?

Apart from the obvious reduction of code. Destructing enables faster access to nested data. A developer no longer has to iterate over an Array or object multiple times to retrieve properties of its nested children.

Take for example:

render() {
const {error: {errorMsg, errorHappened}, loading } = this.props;
    return (
      <section>
        {loading ? (
          <div className="loader">
            <ClipLoader color={'white'} loading={loading} />
          </div>
        ) : (
          <div className="results">
            {errorHappened ? (
              <h1>{errorMsg}</h1>
            ) : (
                <div>No Error </div>
          </div>)
    </section>

In this case, errMsg and errorHappened are now available to use via destructuring without having to extract this nested data with a loop.

Some React components have multiple ternary operators within its render function. Having single word destrucutured variables vastly improves a components readability.  

This can be as simple as better describing loading and error states:

 <section>
        {loading ? (
          <div className="loader">
            <ClipLoader color={'white'} loading={loading} />
          </div>
        ) : (
          <div className="results">
            {errorHappened ? (
              <h1>{errorMsg}</h1>
            ) : (
                <div>No Error </div>
          </div>)
 </section>

This is also useful as there is both easy access to the error object and its nested properties errorMsg  and errorHappened. Its simple, but implementing it throughout React components enables a project to improve its maintainability and readability. 

Improving readability is more useful then one may initially think. Essentially, the developer is eliminating an additional helper to loop through nested data in React’s props.

Not only cutting down the amount of code used but also providing a component with the exact data properties it needs in readily accessible variables.

As with most ES6 improvements, destructuring aims to make the developers life that bit easier. It is certainly a quality of life improvement when considering the improved readability and reduction of written code.

Among these benefits, destructuring reduces the amount of steps taken to access specific data properties.

This is not exclusive to React.js, ES6’s destructuring is an all round useful JavaScript utility and its benefits are evident when used to simplify the naming of data properties.

If you are looking for a more in depth guide to destructuring check out the MDN docs

Proudly published with Gatsby