Nearby lessons

8 of 43

⚛️ ReactJS – Destructuring Props

📌 What is Destructuring?

What is Destructuring in React?

Destructuring is a feature of JavaScript.

It is used to extract values from arrays or objects and assign them to new variables.

In React, it helps to directly extract props or state variables, making code cleaner and more readable.

In destructuring, it does not change an array or any object. It makes a copy of the desired object or array element by assigning them to new variables.

Later, we can use these new variables in React (class or functional) components.

📌 Without Destructuring

We can access array elements or props manually without destructuring.

Example02
Loading editor…

📌 With Destructuring

We can extract array elements or props easily using destructuring.

Example03
Loading editor…

📌 Skipping Array Elements

We can skip array elements by leaving empty spaces between commas during destructuring.

Example04
Loading editor…

📌 Array Destructuring with Default Values

If the array doesn’t have enough values, we can set default values during destructuring.

Example05
Loading editor…

📌 Object Destructuring with Renaming

We can rename variables while destructuring objects.

Example06
Loading editor…

📌 Object Destructuring with Default Values

If props are missing, we can provide default values while destructuring.

Example07
Loading editor…

📌 Accessing props directly

In this example, we use props directly without destructuring. We access props.name and props.age inside the component.
Example08
Loading editor…

📌 Destructuring inside function body

Here, we first take props and then destructure them inside the function body using let {name, age} = props.
Example09
Loading editor…

📌 Destructuring in function parameter

Here, we destructure props directly inside the function parameter. So we don’t need to use props.name, just use name and age directly.
Example10
Loading editor…

📌 Wrong destructuring with different names

If we destructure props with different variable names (like a and b instead of name and age), the data will not show because props must match the same key names.
Example11
Loading editor…

🧩 Advantages of Destructuring

  • It makes developer’s life easy, by assigning their own variables.
  • Improves readability and sustainability of code
  • Reduces amount of code used in an application
  • Trims steps needed to access data properties
  • Provides components with exact data properties
  • Saves time when iterating over arrays of objects

🧠 Test Your Knowledge

3 Questions
Progress: 0 / 3