Destructure Object In React

Introduction 

Today, we will try to understand what Destructuring is and how we can use it in our application.

What is Destructuring?

Destructuring makes it easy to extract only what is needed. To understand it, suppose we have a refrigerator, and we have to prepare a paneer gravy recipe. Do you take everything out of the refrigerator to make your recipe?

No, you only take out the items you would like to use in your recipe.

Destructuring is the same. We may have an array or object that we are working with, but we only need some of the items out of that array.

How to use Destructuring?

We will try to understand Destructuring in below two ways.

  • Destructuring Array
  • Destructuring Objects

Array Destructuring – This is old way (without Destructuring) of fetching values from an array. Based on index we are getting item.

Below example is with using Destructuring. When Destructuring arrays, the order that variables are declared is important.

If we only want the paneerItem and otherItem we can simply leave out the eggItem but keep the comma.

We can simply print this.

Destructure object in React

Object Destructuring

Old way(without destructure) of doing it by using an object inside a function as given example below.

Destructure object in React

New way (using destructure) of using an object inside a function,

Destructure object in React

We can clearly see what every property is required that only getting fetched from vehicleDetail object in function.

We can simply print it.

Destructure object in React

Summary

Here we covered what Destructuring and how to do it with example of array and object.