top of page
Logo der Online Agentur mdwp

Destructuring Assignment

Destructuring Assignment in React is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. This can be very useful in React as we often need to access deeply nested object properties or array values and bind them to variables.

It improves code readability and reduces the line of code needed to access these values. React often uses Destructuring Assignment when passing in `props` to a React component.

For example, if we have a `Student` object like this,

let Student = {
name: "John",
age: 15,
scores: {
math: 90,
english: 80,
science: 85

We can use destructuring assignment to unpack these properties into distinct variables:

let { name, age, scores } = Student;

// Now we can simply use `name`, `age`, `scores` to access these values:

console.log(name); // Output: "John"
console.log(age); // Output: 15
console.log(scores); // Output: {math: 90, english: 80, science: 85}

Similarly, we can destructure `props` in a React component like this:

function Welcome({name}) {
return <h1>Hello, {name}</h1>;

// Instead of:
// function Welcome(props) {
// return <h1>Hello, {}</h1>;
// }

In the above example, `{name}` in the function arguments directly extracts the `name` property from props passed to the `Welcome` component. This makes the code more concise and readable.

bottom of page