Menu

Destructuring in Reactjs – Why use it?

19 November 2018

What is Destructuring?

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.

The properties loading, errorMsg, and errorHappened have been destructured and reassigned as variables named isLoading, userMessageand 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.

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